[英]Laravel eager load function limit
我具有工作功能,但是,我想限制每個顧問返回的治療次數。
工作示例:
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
功能將其限制為返回的治療總數。
我想將每位顧問的待遇限制為最多3種,而不是總數。
請問我該如何實現?
您有兩個選擇,要么獲取所有相關注釋,然后使用類似於Collection :: map的內容在php中截斷,要么用一個復雜的子查詢替換急切的加載
Laravel中對此沒有本地支持。
我為此創建了一個包: https : //github.com/staudenmeir/eloquent-eager-limit
在父模型和相關模型中都使用HasEagerLimit
特征。
class Consultant extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class Treatment extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
然后,您可以將->take(3)
應用於您的關系。
試試看
Clinic::where('user_id', Auth::id())
->with(['consultants' => function ($query) {
$query
->with(['specialism','treatments'])
->take(3);
}]) ->first();
我在打電話。 因此,請原諒我的代碼格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.