Laravel RelationShip(加入 where)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36956201/
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
Laravel RelationShip (join with where)
提问by gibAlex
I need help with Laravel 5 (using Eloquent)
我需要 Laravel 5 的帮助(使用 Eloquent)
I have 2 tables...
我有两张桌子...
Model Driver drivers
模型驱动程序
- id
- company
- ID
- 公司
Model DriverOnline drivers_online
型号 DriverOnline drivers_online
- id
- name
- driver_id
- ID
- 姓名
- driver_id
I need to search for a result on (company=1 and driver_id=driver.id).
我需要在 (company=1 and driver_id=driver.id) 上搜索结果。
Please help me!
请帮我!
回答by Josh
If you want to only fetch Driver
based on a condition, you can just do this:
如果您只想Driver
根据条件获取,您可以这样做:
Driver::with('online')->where('company', 1)->get();
If the clause is on the relationship, use with
and specify a query on that.
如果子句在关系上,请使用with
并指定查询。
$company = 1;
$drivers = Driver::with(['online' => function($query) use ($company)
{
$query->where('company', $company);
}]);
See "Eager Load Constraints":
https://laravel.com/docs/5.0/eloquent
请参阅“急切负载约束”:https:
//laravel.com/docs/5.0/eloquent
Take note of my use
. This allows you to include variables from the scope into your Closure instance.
注意我的use
. 这允许您将范围内的变量包含到您的 Closure 实例中。
And be aware, if you use either solution, you must set up a relationship. Consult the link I shared with more information on that.
请注意,如果您使用任一解决方案,则必须建立关系。请参阅我分享的链接,了解更多相关信息。
Edit: As per our conversation.
编辑:根据我们的谈话。
$drivers = Driver::where('company_id','=',1)
->with('driversOnline')
->whereHas('driversOnline', function($query) {
$query->where('online','=',1);
})
->get();