如何在Eloquent中组合WHERE子句

用户402841

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

SELECT * FROM table WHERE status = 1 AND (type = 2 OR type = 3 OR type = 4)

我一直无法在Eloquent中找到一种简便的方法。如果我用

Table::where('status', 1)->orWhere('type', 2)->orWhere('type', 3)...

这可以翻译为:

SELECT * FROM table WHERE status = 1 OR type = 2 OR type = 3 OR type = 4

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

爱国者

要对where子句进行分组,您需要将闭包传递给where()方法,并在闭包内添加分组条件。因此,您的代码如下所示:

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

这将生成SQL:

SELECT * FROM tables WHERE status = 1 AND (type = 2 OR type = 3 OR type = 4)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章