在Laravel中,您可以使用以下方法在一个查询中获取相关的数据库条目:
$customer = Customer::with('user')->where([
'id' =>'1'
])->first();
它将返回一个客户及其相关的用户对象。是否可以使用项对此应用筛选器?我认为这是可能的:
$customer = Customer::with('user')->where([
'id' =>'1',
'users.status' => 'activated'
])->first();
但这似乎不起作用,它试图在users表中找到一个列"users.status",而不是一个列状态。
您可以使用Eagle加载约束。它允许您对相关模型执行查询。
像这样:
$customer = Customer::with(['user' => function($query){
$query->where('status', 'activated'); //in the user table
}])->where('id', '1')->first(); //in the customer table
您可以阅读渴望加载常量部分以获取更多信息:
http://laravel.com/docs/4.2/eloquent#eager-加载
您可以这样编写查询:
$customer = Customer::with(['user' => function($q){
$q->whereStatus('activated');
}])->find(1);
假设你的主键是1
,你不需要使用where('id','=','1')->get()
,你可以简单地使用find(1)
,并且为了只为相关表选择一些记录,你使用构造作为with
,同时传递闭包。
除了Shibby先生的答案之外,我还会添加一些代码。我就是这样做的,也许你会觉得有用。
$activities = Activity::with('user')
->with(array('images'=>function($query){
$query->orderBy('sort','ASC');
}))
->with(array('images.titles'=>function($query){
$query->orderBy('language_id','ASC');
}))
->with(array('contents'=>function($query){
$query->orderBy('language_id','ASC');
}))
->with(array('titles'=>function($query){
$query->orderBy('language_id','ASC');
}))
->where('user_id',$user_id)
->whereRaw('DATE(NOW()) between online_from and online_until')
->orderBy('sort', 'ASC')
->get();