Replies: 1 comment 1 reply
-
Check it out: #39067 |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
For
withCount()
method, we can happily define an alias to count on the same relationship multiple times in different context. Example from the official documentation:Create pseudo relationship that can be eager loaded, example:
These "relationships" are then available on the models in the view:
The benefit to this is it avoids our N+1 issues, keeps the filtering and sorting in the database, and keeps the majority of the logic out of the view. As
withCount
set a alias,with
must replay the same behaivor.framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php
Lines 368 to 378 in 09feffb
Current Scenario
Imagine you have a Salesperson with many Leads. Leads have a status of "open" or "completed", and a result of "sale" or "no sale".
You are trying to build a dashboard that shows the
Salesperson's
metrics.It is a simple 1:many relationship between the models.
In your controller you fetch all the
Salesperson
s.In your view you loop through the
Salesperson
s.Because we are calling -
>leads()
as a method and not a property (in order to tack on our additional conditions), this will result in new queries being run for each of these groupings, and we don't benefit from the eager loading we did in the controller.There are 2 ways we could currently handle this. We could create additional constrained relationships in the Model:
and then eager load these in the Controller:
This gets rid of our N+1, but the problem with this is it quickly becomes very verbose and unmanageable.
The other option is to filter in PHP (rather than the query) using the returned Collections. In our controller we revert to our simple eager load on the leads relationship:
and now in our view we use Collection methods to filter out our desired data:
This option benefits from the eager loading, so our query count is very low. However, there is a lot of "logic" in the view, which some people do not like. We also duplicate 2 conditions in our "Close Rate" column that we've already determined. Finally, this does offload the filtering and sorting to PHP rather than the database, which could be undesirable in some scenarios, possibly for performance reasons.
Beta Was this translation helpful? Give feedback.
All reactions