[英]Laravel Relationships (With)
我是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,但是,如果條件為false,則我根本不希望返回任何東西。
這應該為您工作:
$accounts = Account::with('booking')
->whereHas(['booking' => function($q)
{
$q->where('status', 'booked');
}])
->get();
$accounts = Account::with(array('booking' => function($query)
{
$query->where('status', '=', 'booked');
}))
->whereHas(array('booking' => function($query)
{
$query->where('status', '=', 'booked');
}))
->get();
這是另一種方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.