【问题标题】:Laravel Query Builder - where clause equals anything programmaticallyLaravel 查询生成器 - where 子句以编程方式等于任何内容
【发布时间】:2018-11-26 17:35:19
【问题描述】:

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

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

假设我有这个代码:

$foo = 1;

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

如果是$foo = 1,那么它很简单。查询将选择状态为 1 的所有内容。

问:是否可以为$foo 变量分配一些东西,以便选择查询返回每条记录,而不管数据库中的状态如何?

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

$foo = 1;

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

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

【问题讨论】:

    标签: mysql laravel laravel-5 laravel-query-builder


    【解决方案1】:

    你可以试试这样的:

    $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.

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2021-06-26
    • 2021-08-16
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多