Laravel whereDoesntHave() - 多个OR条件

时间:2015-01-21 11:01:03

标签: laravel relationship

在Laravel 4.2中,我有一个名为Product的模型,与其他模型(如Country或Category)有多对多的关系。我想过滤出不完整的产品",这意味着他们没有连接国家或没有连接类别。我可以使用whereDoesntHave()方法过滤掉一个关系。当我在一个查询中使用它两次时会创建AND条件,但我需要OR。我无法在API文档中找到orWhereDoesntHave()方法。我不能将多个关系作为参数传递,因为它期望第一个参数是一个字符串。

我需要这样的事情: $products = Product::whereDoesntHave('categories')->orWhereDoesntHave('countries')->get();

有没有办法让whereDoesntHave()符合多个OR条件?

4 个答案:

答案 0 :(得分:12)

您可以使用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();

答案 1 :(得分:3)

使用

Product::whereDoesntHave('categories')->doesntHave('countries', 'or')->get();

Laravel源代码:

whereDoesntHave https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#L654 电话 https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#L628 内部。

答案 2 :(得分:2)

从Laravel 5.5开始,有一个orWhereDoesntHave函数。

您可以这样使用它

Product::Product::whereDoesntHave('categories', function($q){ //... })
                  ->orWhereDoesntHave('countries', function($q){//...})
                  ->get();

从您的示例看来,您似乎没有使用where子句,因此您可以只使用

Product::Product::doesntHave('categories')
                  ->ordoesntHave('countries')
                  ->get();

答案 3 :(得分:1)

假设我们有 Authors 和 Books,具有 1-n 关系——一个 Author 可以拥有一本书或多本书。这是它在 app\Author.php 中的样子:

 public function books()
    {
        return $this->hasMany(\App\Book::class, 'author_id');
    }

现在,如果我们只想显示那些至少拥有一本书的作者怎么办?很简单,有方法 has():

$authors = Author::has('books')->get();

同样,还有一种相反的方法——如果我们只想查询作者而没有任何书籍怎么办?使用 donthave():

  $authors = Author::doesnthave('books')->get();

它不仅方便,而且超级容易阅读和理解,即使您不是 Laravel 开发人员,对吗?