Laravel 过滤值时的条件子句
Laravel conditional clause when for filtering value
我有一个事件 table,状态为 o 或 1。
我必须过滤状态为 1,0 或 ALL 的事件。
我尝试使用 laravel 当条件子句时,它不适用于零值,其他条件有效。
$status = Input::get('status');
$events = DB::table('events')
->select('events.*')
->when($status, function ($query) use ($status) {
return $query->where("events.status",$status);
})
->get();
in_array
when
方法中使用的函数试试这个
because 0(zero) means(false) by default understand so try to use inner function in when method
if didn't pass status then set default value as 2
or any number but not 0,1 and null
$status = Input::has('status') ? Input::get('status') : 2;
$events = DB::table('events')->select('events.*')
->when(in_array($status,[0,1]), function ($query) use ($status) {
return $query->where("events.status",$status);
})->get();
second way create a new function
function checkStatus($status,$array) {
if(isset($status)) {
return in_array($status,$array);
}
return false;
}
$events = DB::table('events')->select('events.*')
->when(checkStatus($status,[0,1]), function ($query) use ($status) {
return $query->where("events.status",$status);
})->get();
我有一个事件 table,状态为 o 或 1。
我必须过滤状态为 1,0 或 ALL 的事件。
我尝试使用 laravel 当条件子句时,它不适用于零值,其他条件有效。
$status = Input::get('status');
$events = DB::table('events')
->select('events.*')
->when($status, function ($query) use ($status) {
return $query->where("events.status",$status);
})
->get();
in_array
when
方法中使用的函数试试这个
because 0(zero) means(false) by default understand so try to use inner function in when method
if didn't pass status then set default value as
2
or any number but not0,1 and null
$status = Input::has('status') ? Input::get('status') : 2;
$events = DB::table('events')->select('events.*')
->when(in_array($status,[0,1]), function ($query) use ($status) {
return $query->where("events.status",$status);
})->get();
second way create a new function
function checkStatus($status,$array) {
if(isset($status)) {
return in_array($status,$array);
}
return false;
}
$events = DB::table('events')->select('events.*')
->when(checkStatus($status,[0,1]), function ($query) use ($status) {
return $query->where("events.status",$status);
})->get();