且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在雄辩中结合WHERE子句

更新时间:2023-10-23 14:19:52

要组合这样的子句,您需要将闭包传递给 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)