2015-01-21 556 views
4

在Laravel 4.2中,我有一個名爲Product的模型,其中包含許多與其他模型(如Country或Category)的多對多關係。我想過濾掉「不完整」的產品,這意味着它們沒有關聯的國家或沒有關聯的類別。我可以使用whereDoesntHave()方法過濾掉一個關係。當我在一次查詢中使用它兩次時,它會創建AND條件,但我需要OR。我在API文檔中找不到orWhereDoesntHave()方法。我不能將多個關係作爲參數傳遞,因爲它期望第一個參數是一個字符串。Laravel whereDoesntHave() - 多個或條件

我需要的是這樣的: $products = Product::whereDoesntHave('categories')->orWhereDoesntHave('countries')->get();

有什麼辦法才達到whereDoesntHave()OR條件?

回答

5

您可以使用doesntHave並指定布爾運算符:

$products = Product::doesntHave('categories')->doesntHave('countries', 'or')->get(); 

其實你只需要whereDoesntHave如果你想在一個封閉通過檢查其中是否存在之前過濾的相關模型。如果你想這樣做,你可以通過封閉作爲第三個參數:

$products = Product::doesntHave('categories', 'or', function($q){ 
    $q->where('active', false); 
})->doesntHave('countries', 'or')->get(); 
+0

謝謝,我在閱讀API時錯過了'doesntHave()'。你的第一個代碼示例正是我需要的。 – KazikM 2015-01-21 13:33:26