首页 > 解决方案 > Laravel Eloquent Query 使用 WHERE 一组条件或 OR 另一组条件以及一些常见条件?

问题描述

我必须在我的 Laravel 项目中进行 sql 操作。

除了提到的条件外,我还有一些常见的条件。我知道如何在原始 mysql 中编写它。

所以,例如我需要的是

我怎么说WHERE Condition X AND Condition Y AND ( (a = 1 and b =1 ) OR (c = 1 AND d = 1) ) 使用 laravel 查询格式?

标签: phpmysqllaraveleloquentlaravel-query-builder

解决方案


考虑以下语法:

DB::table('yourTable')
    ->where('x', '=', '1')
    ->where('y', '=', '1')
    ->where(function($q1)
    {
        $q1->where(function($q2)
        {
            $q2->where('a', '=', '1')
            ->where('b', '=', '1');
        })
        ->orWhere(function($q2)
        {
            $q2->where('c', '=', '1')
            ->where('d', '=', '1');
        });
    });

如果您更喜欢 More Readable Syntaxwhere将接受数组作为参数

DB::table('yourTable')
            ->where('x','=',1)
            ->where('y','=',1)
            ->where(function($queryBuilder){
                $queryBuilder->where([
                    ['a','=',1],
                    ['b','=',1],
                ])
                ->orWhere([
                    ['c','=',1],
                    ['d','=',1],
                ]);
            });

推荐阅读