在 Laravel 中结合 AND/OR eloquent 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15653216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Combining AND/OR eloquent query in Laravel
提问by SUB0DH
How can I write following or similar kind of queries using Eloquent?
如何使用 Eloquent 编写以下或类似的查询?
SELECT * FROM a_table WHERE (a LIKE %keyword% OR b LIKE %keyword%) AND c = 1 AND d = 5
SELECT * FROM a_table WHERE (a LIKE %keyword% OR b LIKE %keyword%) AND c = 1 AND d = 5
I couldn't combine AND/OR in the way I wanted by chaining where & or_where functions.
我无法通过链接 where & or_where 函数以我想要的方式组合 AND/OR。
回答by Florent Poujol
You can nest where clauses : http://laravel.com/docs/database/fluent#nested-where
您可以嵌套 where 子句:http: //laravel.com/docs/database/fluent#nested-where
Model::where(function($query)
{
$query->where('a', 'like', 'keyword');
$query->or_where('b', 'like', 'keyword');
})
->where('c', '=', '1');
This should produce : SELECT * FROM models WHERE (a LIKE %keyword% OR b LIKE %keyword%) AND c = 1
这应该产生: SELECT * FROM models WHERE (a LIKE %keyword% OR b LIKE %keyword%) AND c = 1
回答by aowie1
For a more accurate answer to the example:
对于示例的更准确答案:
$val = '%keyword%';
A_Table_Model::where(function($query) use ($val)
{
$query->where('a', 'like', $val);
$query->or_where('b', 'like', $val);
})
->where('c', '=', 1)
->where('d', '=', 5)
->get();
Note: This is Laravel 3 syntax, use camelCase orWhere() for Laravel 4
注意:这是 Laravel 3 的语法,Laravel 4 使用camelCase orWhere()
回答by Kornel
In Laravel 5.1+ this will also do the job and looks cleaner:
在 Laravel 5.1+ 中,这也可以完成工作并且看起来更干净:
Model::where(function($query) {
$query->where('a', 'like', 'keyword');
$query->or_where('b', 'like', 'keyword');
})->where('c', '=', '1')->get();
回答by Rob Gordijn
You can use DB::raw()
in the first where()
to put in the like/or statement.
您可以使用DB::raw()
in 第一个where()
放入 like/or 语句。