【问题标题】:Laravel: Fetch with where filter on "with"Laravel:在“with”上使用where过滤器获取
【发布时间】:2014-10-16 23:37:54
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

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

    像这样:

    $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-loading

    【讨论】:

      【解决方案2】:

      你可以这样写你的查询:

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

      假设你的主键是1,你不需要使用where('id','=','1')->get(),你可以简单地使用find(1),并且只为相关表选择一些记录,你使用构造作为with传递闭包。

      【讨论】:

        【解决方案3】:

        除了 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();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-11-05
          • 2017-01-12
          • 2022-08-06
          • 2019-11-19
          • 2021-07-12
          • 2018-10-08
          • 2020-12-14
          相关资源
          最近更新 更多