i have a model User and i want search user by city but if the city varible is null a want all user
我有一个模型用户,我想按城市搜索用户但如果城市变量为空,我想要所有用户
my code like this
这样我的代码
User::where('city', $city)->orderBy('created_at')->paginate(10);
but if the city varible is null the query return nothing
但是如果城市变量为空,查询将不返回任何内容
i thy this
我你这
User::doesntHave('city')->get();
and this
这
User::whereHas('city')->get();
I know i can read my code like this
我知道我可以这样读我的代码
if($city){
User::where('city', $city)->orderBy('created_at')->paginate(10);
} else {
User::orderBy('created_at')->paginate(10);
}
but a want add other varible in my query and is not perfect
但在我的查询中添加其他变量并不是完美的
1 个解决方案
#1
3
1. You could use where()
closure:
1。您可以使用where()闭包:
User::where(function ($q) use($city) {
if ($city) {
$q->where('city', $city);
}
})->orderBy('created_at')->paginate(10);
2. You could use when()
:
2。您可以使用当():
User::when($city, function ($q) use ($city) {
return $q->where('city', $city);
})->orderBy('created_at')->paginate(10);
3. Do this:
3所示。这样做:
$users = User::orderBy('created_at');
if ($city) {
$users = $users->where('city', $city);
}
$users = $users->paginate(10);
#1
3
1. You could use where()
closure:
1。您可以使用where()闭包:
User::where(function ($q) use($city) {
if ($city) {
$q->where('city', $city);
}
})->orderBy('created_at')->paginate(10);
2. You could use when()
:
2。您可以使用当():
User::when($city, function ($q) use ($city) {
return $q->where('city', $city);
})->orderBy('created_at')->paginate(10);
3. Do this:
3所示。这样做:
$users = User::orderBy('created_at');
if ($city) {
$users = $users->where('city', $city);
}
$users = $users->paginate(10);