我正在尝试使用Eloquent ORM在Laravel 4中构建一个查询,该查询简单地匹配标准中的所有字段。我有下面的代码,目前返回的数据匹配任何条件,而不是所有的条件,或,而不是AND,如果你愿意。
$names = Input::get('names');
$company = Input::get('company');
$contacts = Contact::where(function($query) use ($names, $tags, $type, $sector, $company)
{
if (!empty($names)) {
$query->where('firstname', 'LIKE', "%{$names}%")
->orWhere('lastname', 'LIKE', "%{$names}%");
}
if (!empty($company)) {
$query->where('company', 'LIKE', "%{$company}%");
}
})
->paginate(100);
return View::make('index')->with('contacts', $contacts)->with('searchingFlag', $searchingFlag)->with('names', $names)->with('tags', $tags)->with('type', $type)->with('sector', $sector)->with('company', $company);
因此,我认为,我在这里所做的是声明结果必须匹配name字段和company字段中的一个,如果设置了其中一个,但是如上所述,返回的结果匹配其中一个子句,而不是两个子句。
有谁能帮我弄清楚是怎么回事吗?谢谢
您需要在以下位置嵌套:
if (!empty($names)) {
$query->where(function ($q) use ($names) {
$q->where('firstname', 'LIKE', "%{$names}%")
->orWhere('lastname', 'LIKE', "%{$names}%");
}
}
这将导致:
SELECT ... WHERE (firstname like .. OR lasname like ..) AND company ...
if(!empty($names)) {
$query->whereRaw('firstname LIKE "%{$names}%" OR lastname LIKE "%{$names}%" ');
}