Laravel 查询生成器 - where 子句以编程方式等于任何内容

Laravel Query Builder - where clause equals anything programmatically

我正在使用 Laravel 5.6 - 查询生成器。

是否可以在查询生成器 where 语句中以编程方式使值等于所有内容?

假设我有这个代码:

$foo = 1;

DB::table('users')
  ->select('*')
  ->where('status', '=', $foo)
  ->get();

如果$foo = 1那么就很简单了。查询将 select 状态为 1 的所有内容。

Q: 是否可以为 $foo 变量赋值,以便 select 查询 returns 每条记录而不考虑状态来自数据库?

当然,我可以用这样的 2 个查询语句实现它:

$foo = 1;

if ($foo === null) {
  DB::table('users')
    ->select('*')
    ->get();
} else {
  DB::table('users')
    ->select('*')
    ->where('status', '=', $foo)
    ->get();
}

但是,我正在寻找更短/更有效的解决方案。是否有可能 - 在 Where 语句中不使用 raw code

您可以尝试这样的操作:

$query = DB::table('users')->select('*');

// $foo = 'get it...';

if ($foo) {
    $query->where('status', $foo);
}

$result = $query->get();

甚至更多laravel-ish:

$result = DB::table('users')->select('*')
          ->when($foo, function ($query) use ($foo) {
              return $query->where('status', $foo);
          })
          ->get();

Check more here.