【问题标题】:Laravel whereDoesntHave() - multiple OR conditionsLaravel whereDoesntHave() - 多个 OR 条件
【发布时间】:2015-03-19 20:59:54
【问题描述】:

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

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

有没有办法在多个OR 条件下实现whereDoesntHave()

【问题讨论】:

    标签: laravel relationship


    【解决方案1】:

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

    【讨论】:

    • 谢谢,我在阅读 API 时错过了doesntHave()。您的第一个代码示例正是我所需要的。
    【解决方案2】:

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

    你可以这样使用它

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

    从你的例子看来你没有使用 where 子句,所以你可以只使用

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

    【讨论】:

      【解决方案3】:

      使用

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

      Laravel 源代码:

      哪里没有https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#L654 来电 https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#L628 内部。

      【讨论】:

      • 谢谢,看来我错过了doesntHave() 方法及其第二个参数。
      【解决方案4】:

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

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

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

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

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

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

      它不仅方便,而且超级容易阅读和理解,即使你不是 Laravel 开发者,对吧?

      【讨论】:

        猜你喜欢
        • 2021-02-20
        • 1970-01-01
        • 2018-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        • 2020-05-22
        相关资源
        最近更新 更多