【问题标题】:Laravel Relationships (With)Laravel 关系(与)
【发布时间】:2017-03-04 15:41:03
【问题描述】:

我对 Laravel 还很陌生。

我正在尝试使用 Laravel 的 Eloquent 查询构建器从我的数据库中提取数据,我可以毫无问题地提取所有数据,但是我想在关系中的第二个表中添加一个约束,这应该导致根本没有数据返回如果不是真的。

但是,当我尝试这样做时,我没有返回第二个表数据,但仍返回初始表数据,这对我的视图造成了严重破坏。

这就是我所拥有的:

$accounts = Account::with(array('booking' => function($query)
{
     $query->where('status', '=', 'booked');
}))
->get();

我确保在模型中设置了关系,但是由于某种原因,我得到了这样的响应:

  ["attributes":protected]=>
  array(4) {
    ["booking_id"]=>
    int(1)
    ["account_paid"]=>
    int(1)
    ["created_at"]=>
    string(19) "2016-10-22 11:10:49"
    ["updated_at"]=>
    string(19) "2016-10-22 11:10:49"
  }
  ["original":protected]=>
  array(4) {
    ["booking_id"]=>
    int(1)
    ["account_paid"]=>
    int(1)
    ["created_at"]=>
    string(19) "2016-10-22 11:10:49"
    ["updated_at"]=>
    string(19) "2016-10-22 11:10:49"
  }
  ["relations":protected]=>
  array(1) {
    ["booking"]=>
    NULL
  }

将预订设置为空,但是如果条件为假,我想要什么都不返回。

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    这应该适合你:

    $accounts = Account::with('booking')
        ->whereHas(['booking' => function($q)
        {
            $q->where('status', 'booked');
        }])
        ->get();
    

    【讨论】:

    • 完美!正是我想要的!谢谢! :)
    【解决方案2】:
    $accounts = Account::with(array('booking' => function($query)
         {
              $query->where('status', '=', 'booked');
          }))
         ->whereHas(array('booking' => function($query)
         {
              $query->where('status', '=', 'booked');
          }))
        ->get();
    

    这是另一种方式。

    【讨论】:

    • 这几乎是完美的!在看到他的帖子之前,我实际上用它来找出 Alexey Mazenin 的解决方案:D 感谢您的帮助 :)
    • :D 没问题,:)
    猜你喜欢
    • 2016-11-21
    • 2021-09-24
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2014-02-01
    • 2018-02-15
    相关资源
    最近更新 更多