如何在 Eloquent 中组合 WHERE 子句 [英] How to combine WHERE clauses in Eloquent

查看:22
本文介绍了如何在 Eloquent 中组合 WHERE 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to have this kind of query in Eloquent:

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

我一直无法在 Eloquent 中找到一种简单的方法来执行此操作.如果我使用

I've been unable to find an easy way of doing this in Eloquent. If I use

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

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

Which is not what I need. Creating a query scope for 'status = 1' also gets me the same results. How can I run this query in Eloquent?

推荐答案

要像这样对 where 子句进行分组,您需要将闭包传递给 where() 方法,并在其中添加分组条件关闭.因此,您的代码将类似于:

To group where clauses like that, you need to pass a closure to the where() method, and add your grouped conditions inside the closure. So, your code would look something like:

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)

这篇关于如何在 Eloquent 中组合 WHERE 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆