如何在 Eloquent 中组合 WHERE 子句

Rei*_*ica 4 laravel eloquent

我想在 Eloquent 中进行这种查询:

SELECT * FROM table WHERE status = 1 AND (type = 2 OR type = 3 OR type = 4)
Run Code Online (Sandbox Code Playgroud)

我一直无法在 Eloquent 中找到一种简单的方法来做到这一点。如果我使用

Table::where('status', 1)->orWhere('type', 2)->orWhere('type', 3)...
Run Code Online (Sandbox Code Playgroud)

这转化为:

SELECT * FROM table WHERE status = 1 OR type = 2 OR type = 3 OR type = 4
Run Code Online (Sandbox Code Playgroud)

这不是我需要的。为 'status = 1' 创建查询范围也会得到相同的结果。如何在 Eloquent 中运行此查询?

pat*_*cus 6

要像这样对 where 子句进行分组,您需要将闭包传递给该where()方法,并在闭包中添加分组条件。所以,你的代码看起来像:

Table::where('status', 1)->where(function ($q) {
    return $q->where('type', 2)->orWhere('type', 3)->orWhere('type', 4);
});
Run Code Online (Sandbox Code Playgroud)

这将生成 SQL:

SELECT * FROM tables WHERE status = 1 AND (type = 2 OR type = 3 OR type = 4)
Run Code Online (Sandbox Code Playgroud)