Laravel eager load function limit

别说谁变了你拦得住时间么 提交于 2021-01-16 04:21:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!