如果变量为null,Laravel eloquent将获取所有内容

时间:2017-12-29 20:04:56

标签: php mysql laravel

我有一个模型用户,我希望按城市搜索用户,但如果城市变量为空,则需要所有用户

我的代码就像这样

User::where('city', $city)->orderBy('created_at')->paginate(10);

但如果city varible为null,则查询不返回任何内容

我是你的

 User::doesntHave('city')->get();

和这个

User::whereHas('city')->get();

我知道我可以像这样阅读我的代码

  if($city){
     User::where('city', $city)->orderBy('created_at')->paginate(10);
  } else {
    User::orderBy('created_at')->paginate(10);
}

但是想要在我的查询中添加其他变量并且不完美

1 个答案:

答案 0 :(得分:4)

1。您可以使用where() closure

User::where(function ($q) use($city) {
    if ($city) {
        $q->where('city', $city);
    }
})->orderBy('created_at')->paginate(10);

2。您可以使用when()

User::when($city, function ($q) use ($city) {
    return $q->where('city', $city);
})->orderBy('created_at')->paginate(10);

3. 执行此操作:

$users = User::orderBy('created_at');

if ($city) {
    $users = $users->where('city', $city);
}

$users = $users->paginate(10);