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?
您有两个选择,要么获取所有相关注释,然后使用类似于Collection :: map的内容在php中截断,要么用一个复杂的子查询替换急切的加载
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.