【问题标题】:How in laravel eloquent make query with multiple 'and'?laravel eloquent 如何使用多个“和”进行查询?
【发布时间】:2018-12-11 21:41:19
【问题描述】:

我有这个问题:

SELECT * 
FROM `groups` 
WHERE `status` = 1 
    AND `active` != 1 
    AND (`approved` != 1 OR `approved` IS NULL)

我在查询生成器中尝试了这个,但不知道如何正确实现

这是我的查询生成器:

Group::where([['status', '=', 1], ['active', '!=', 1]])
    ->where([['approved', '!=', 1]])
    ->orWhereNull()
    ->get();

【问题讨论】:

标签: php laravel eloquent


【解决方案1】:

您应该使用带有闭包的 where 来对参数进行分组。 https://laravel.com/docs/5.7/queries#parameter-grouping

$data = Group::where(function($query){
        $query
            ->where('approved', '!=', 1)
            ->orWhereNull('approved');
    })
    ->where('status', 1)
    ->where('active', '!=', 1)
    ->get();

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    $articles = \App\Article::where('foo', 'bar')
        ->where('color', 'blue')
        ->orWhere('name', 'like', '%John%')
        ->whereIn('id', [1, 2, 3, 4, 5])
        ->get();
    

    【讨论】:

    • 似乎不足以帮助作者。如果他已经为您提供了他所拥有的代码示例,请尝试对其进行处理,看看您如何改进它。
    【解决方案3】:

    试试这个

     Group::where('status', 1)
        ->where('active', '!=', 1)
        ->where(function($query){
           $query->where('approved', '!=', 1)
                ->orWhereNull('approved')
        })->get();
    

    在 laravel 的闭包中使用 where see

    【讨论】:

      【解决方案4】:

      试试这个

      Group::where('status', 1)->where('active', '!=', 1)->where('approved', '!=', 1)
      ->orWhere('status', 1)->where('active', '!=', 1)->where('approved', NULL)
      ->get();
      

      $x = Group::where(function($q){
              $q->where('approved', '!=', 1)
                ->orWhereNull('approved')
              })
                 ->where('status', 1)->where('active', '!=', 1)
                 ->get();
      

      【讨论】:

        猜你喜欢
        • 2020-02-20
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 2013-03-04
        • 1970-01-01
        • 1970-01-01
        • 2016-12-01
        相关资源
        最近更新 更多