问题
I have a working function, however, I'd like to limit the number of treatments, per consultant, that are returned.
Working Example:
Clinic::where('user_id', Auth::id())
->with('consultants.specialism', 'consultants.treatments')
->first();
Proposed (but not working) example:
Clinic::where('user_id', Auth::id())
->with('consultants.specialism')
->with(['consultants.treatments' => function ($query) {
$query->take(3);
}])
->first();
Unfortunately, the take
or limit
function, limits it to the total number of treatments returned.
What I would like is to limit each consultant's treatments to a maximum of 3, not the total.
How can I achieve this please?
回答1:
There is no native support for this in Laravel.
I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit
trait in both the parent and the related model.
class Consultant extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class Treatment extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
Then you can apply ->take(3)
to your relationship.
回答2:
You have two options, either fetch all related comments and truncate in php using something like Collection::map or replace the eager loading with a complex sub-query
回答3:
Try this out
Clinic::where('user_id', Auth::id())
->with(['consultants' => function ($query) {
$query
->with(['specialism','treatments'])
->take(3);
}]) ->first();
I'm on my phone. So excuse my code formatting.
来源:https://stackoverflow.com/questions/41664645/laravel-eager-load-function-limit