Laravel:使用"取得"上的过滤器。

时间:2014-10-16 15:18:10

标签: php laravel eloquent

在Laravel中,您可以使用with方法在一个查询中获取相关的数据库条目:

$customer = Customer::with('user')->where([
    'id' =>'1'
])->first();

将返回客户及其相关的用户对象。是否可以使用项目对此应用过滤器?我认为这是可能的:

$customer = Customer::with('user')->where([
    'id' =>'1',
    'users.status' => 'activated'
])->first();

但这似乎不起作用,它试图在users表中找到一列“users.status”而不是列状态。

3 个答案:

答案 0 :(得分:2)

您可以使用Eager加载约束。它允许您对相关模型执行查询。

像这样:

$customer = Customer::with(['user' => function($query){
    $query->where('status', 'activated'); //in the user table
}])->where('id', '1')->first(); //in the customer table

您可以阅读渴望加载的constaints部分以获取更多信息:

http://laravel.com/docs/4.2/eloquent#eager-loading

答案 1 :(得分:2)

您可以这样编写查询:

$customer = Customer::with(['user' => function($q){
    $q->whereStatus('activated'); 
}])->find(1);

假设您的主键是1,您不需要使用where('id','=','1')->get(),只需使用find(1)并仅选择相关表格的某些记录即可将构造用作{ {1}}也通过关闭。

答案 2 :(得分:1)

除了MrShibby的回答之外,我还会提交一些代码。 我就是这样做的,也许你发现它很有用。

$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();