Laravel 查询:Where 子句中的条件值

Laravel Query: Conditional value in Where Clause

我有这个问题

$timezone ='';

if(!empty(\Request::get('timezone')))
{
   $timezone = \Request::get('timezone')
}else
{
   $timezone = 'users.timezone'
}


$users = DB::table('users')
                ->where('timezone', $timezone)
                ->get();

当条件为空或未定义时如何保持显示结果?

使用when()方法:

DB::table('users')->when($request->timezone, function($q) {
        return $q->where('timezone', request()->timezone)
    })
    ->get();

The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be execute

或者,您可以使用 where 闭包。