php Laravel 或哪里
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18660180/
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
Laravel or where
提问by Matthijn
Currently I am working on a project in Laravel but I am stuck.I want to create a SQL statement like this:
目前我正在 Laravel 中开展一个项目,但我被卡住了。我想创建一个这样的 SQL 语句:
SELECT * FROM SPITems WHERE publisher_id=? AND feed_id=? AND (title LIKE '%?%' OR description LIKE '%?%')
Now I have this code:
现在我有这个代码:
$query = SPItem::orderBy('title');
if(isset($_GET['publisherID']) && is_numeric($_GET['publisherID']))
{
$query = $query->where('publisher_id', $_GET['publisherID']);
}
if(isset($_GET['productFeedID']) && is_numeric($_GET['productFeedID']))
{
$query = $query->where('program_id', $_GET['feedID']);
}
if(isset($_GET['search']))
{
$query = $query->orWhere('title', 'like', '%' . $_GET['search'] . '%');
$query = $query->where('description', 'like', '%' . $_GET['search'] . '%');
}
But that generates:
但这会产生:
SELECT * FROM SPITems WHERE (publisher_id=? AND feed_id=?) OR (title LIKE '%?%') AND description LIKE '%?%'
How can I get the correct "or" order?
我怎样才能得到正确的“或”顺序?
回答by dcro
Check out the Parameter Groupingsection in the docs:
查看文档中的参数分组部分:
https://laravel.com/docs/master/queries#parameter-grouping
https://laravel.com/docs/master/queries#parameter-grouping
It explains how to group conditions in the WHERE clause.
它解释了如何在 WHERE 子句中对条件进行分组。
It should be something like:
它应该是这样的:
if(isset($_GET['search']))
{
$query = $query->where(function($query){
$query->where('title', 'like', '%' . $_GET['search'] . '%')
->orWhere('description', 'like', '%' . $_GET['search'] . '%');
});
}
回答by srsajid
You can use whereRaw
您可以使用 whereRaw
SPItem::whereRaw(" publisher_id=? AND feed_id=? AND (title LIKE '%?%' OR description LIKE '%?%')", array(?,?,?,?))