Laravel关系(附)

问题描述 投票:2回答:2

我对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
  }

预订设置为null,但是如果条件为假,我想要的是什么都没有返回。

php laravel eloquent
2个回答
2
投票

这应该适合你:

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

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

这是另一种方式。

© www.soinside.com 2019 - 2024. All rights reserved.