2016-10-22 85 views
2

我對Laravel相當陌生。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,但是,如果條件爲假,我想要的是沒有任何回報。

回答

2

這應該爲你工作:

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

完美!正是我正在尋找的!謝謝! :) – user1785684

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

這是另一種方法。

+0

這幾乎是完美的!我真的用它來找出Alexey Mazenin的解決方案,只是在看到他的帖子之前:D感謝您的幫助:) – user1785684

+0

:D沒問題,:) –