Laravel急切的加载功能限制 [英] Laravel eager load function limit
问题描述
我有一个工作职能,但是,我想限制每个顾问返回的治疗次数.
I have a working function, however, I'd like to limit the number of treatments, per consultant, that are returned.
工作示例:
Clinic::where('user_id', Auth::id())
->with('consultants.specialism', 'consultants.treatments')
->first();
建议(但不起作用)的示例:
Clinic::where('user_id', Auth::id())
->with('consultants.specialism')
->with(['consultants.treatments' => function ($query) {
$query->take(3);
}])
->first();
不幸的是, take
或 limit
函数将其限制为返回的治疗总数.
Unfortunately, the take
or limit
function, limits it to the total number of treatments returned.
我想将每位顾问的待遇限制为最多3个,而不是总数.
What I would like is to limit each consultant's treatments to a maximum of 3, not the total.
请问如何实现?
推荐答案
Laravel中对此没有本地支持.
There is no native support for this in Laravel.
我为此创建了一个程序包: https://github.com/staudenmeir/eloquent-渴望极限
I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit
在父模型和相关模型中均使用 HasEagerLimit
特性.
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;
}
然后,您可以将-> take(3)
应用于您的关系.
Then you can apply ->take(3)
to your relationship.
这篇关于Laravel急切的加载功能限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!