It was brought to my attention in a code review, instead of:
Version A: $someModel->with('relationMethodA.id,some_field, created_at')
rather use this notation:
Version B $someModel->with(['relationMethodA' => fn($q) => $q->select('relationMethodA.id,some_field, created_at')])
.
I wonder because both give the same result. Are there any reasons to use one or the other?
4
Answers
When using ‘with()’ with an array the array parameter allows you to pass multiple variables to the view, which can then be accessed within the view using the specified keys For example:
When using with() with a string parameter it is typically used in the context of a single variable or data being passed to a view. For example:
It depends on your specific use case and the number of variables you need to pass to the view.
As what document said in Constraining Eager Loads
You can see in the official document example:
Only those posts with the word
code
in their title will load for each user.This will load the relation "relationMethodA" with this specific columns only:
‘relationMethodA.id,some_field, created_at’, However Version A will load all columns. This might be a good option when you don’t need whole data in your relations.
Well, Indeed both queries return the same result but there’s very slight and neglible perfromance measure which makes Version A to be faster.
However Version B will allow you to add more complexity in the query.
When eager loading, the first syntax you illustrated should use a colon;
So this loads just three of the columns and is the same as adding a select statement to the relationship, as you did in the second example
Note that you can also pass an array of related models;
as well as just passing multiple parameters
and nested relations
personally, I would always use the colon to specify the columns to load as this is far more concise and readable than the closure approach, although this can be useful for adding additional conditions or even query scopes.