我正在尝试使用eloquent搜索两个可选表:
$users = User::where('ProfileType', '=', 2)
->where(function($query) {
$query->where('BandName', 'LIKE', "%$artist%");
$query->or_where('Genre', 'LIKE', "%$genre%");
})->get();
当用户执行空搜索时,这可以很好地返回所有结果,但我不知道如何调整它以便在存在时搜索bandname,反之亦然。
答案 0 :(得分:8)
只是为了解释下面的答案会发生什么:
Eloquent在这里做了一件棘手的事情:当你致电User::where(...)
时,它会返回一个Database\ Query对象。这与构造SQL查询的可链接对象DB::table('users')->where(...)
基本相同。
所以:
// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
$query->where(function($query) {
// Adds a clause to the query
if ($artist = Input::get('artist')) {
$query->where_nested('BandName', 'LIKE', "%$artist%", 'OR');
}
// And another
if ($genre = Input::get('genre')) {
$query->where_nested('Genre', 'LIKE', "%$genre%", 'OR');
}
});
// Executes the query and fetches it's results
$users = $query->get();
答案 1 :(得分:2)
建立在Vinicius'回答这里有用的:
// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
// Adds a clause to the query
if ($artist = Input::get('artist')) {
$query->where('BandName', 'LIKE', "%$artist%");
// Temp Usernamesearch
$query->or_where('NickName', 'LIKE', "%$artist%");
}
// Genre - switch function if artist is not empty
if ($genre = Input::get('genre')) {
$func = ($artist) ? 'or_where' : 'where';
$query->$func('Genre', 'LIKE', "%$genre%");
}
// Executes the query and fetches it's results
$users = $query->get();
事实证明,如果未设置$ artist,则第二个可选字段必须使用or_where。
感谢您的帮助
答案 2 :(得分:0)
我认为这就是你所追求的。您的视图将有一个表单来搜索艺术家/流派,其中一个或另一个可以设置,或两者都有,或者没有。
$users = User::where('ProfileType', '=', 2);
if (Input::has('artist')) {
$users = $users->where('BandName', 'LIKE', '%'.Input::get('artist').'%');
}
if (Input::has('genre')) {
$users = $users->where('Genre', 'LIKE', '%'.Input::get('genre').'%');
}
$users = $users->get();