有条件的急切加载 - Laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40533776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eager loading with conditional - Laravel
提问by Juliatzin
I have this query:
我有这个查询:
$tournament = Tournament::with(
'championships',
'championships.settings',
'championships.category',
'championships.tree.users',
)->first();
Right now, it gives me the tournament with all attached championships.
现在,它给了我所有附加锦标赛的锦标赛。
What I need is to get the tournament but only with the championship which match the $request->championshipId that I have.
我需要的是获得锦标赛,但只能获得与我拥有的 $request->championshipId 匹配的冠军。
Off course, I also want this filter in all the other relations ('championships.settings', 'championships.category','championships.tree.users') Any idea?
当然,我还希望在所有其他关系中使用此过滤器('championships.settings'、'championships.category'、'championships.tree.users')知道吗?
回答by Saumya Rastogi
You can use Constraining Eager Loading
like this:
你可以这样使用Constraining Eager Loading
:
$tournaments = Tournament::with(['championships' => function ($query) {
$query->where('something', 'like', '%this%');
},
'championships.settings' => function ($query) {
$query->where('something', 'like', '%this%');
},
...])->get();
Hope this helps!
希望这可以帮助!
回答by Eric Tucker
Load the relations in the subquery constraint:
加载子查询约束中的关系:
$tournament = Tournament::with(['championships' => function($query) use ($request) {
return $query->where('id', $request->championshipId)
->with([
'settings',
'category',
'tree.users'
]);
}])->first();
回答by sh6210
there is another way of doing this, first grab data.
还有一种方法可以做到这一点,首先抓取数据。
$user = User::all();
then add the condition to load relation
然后将条件添加到负载关系
if(condition){
$user->load('profile')
}
Or you can use WHENto conditionally load the relational data.
或者您可以使用WHEN有条件地加载关系数据。
$doctors = new Doctor();
$doctors->with( 'subSpeciality' )
->when( $searchKey, function ( $query ) use ( $searchKey ) {
return $query->where( 'name', 'like', "%$searchKey%" )
->orwhere( 'code', 'like', "%$searchKey%" )
->orwhere( 'sfdc_code','like',"%$searchKey%" );
} );