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

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

问题描述

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

我一直找不到一个简单的方法在雄辩中这样做。如果我使用

  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中运行此查询?

解决方案

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

  Table :: where('status',1) - > where ($ 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)


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)

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)...

This this translates to:

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

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?

解决方案

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);
});

This will generate the SQL:

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

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

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