[英]How to check the column before executing the query in Laravel
就像問題的標題一樣,我想在Laravel中執行查詢之前先檢查表中的一列,例如檢查“部門”字段是否為空然后執行查詢,如果位置“字段”為空然后執行一個查詢查詢。 我想檢查表中的列是否為空,而不是數據變量。
DB::table('tasks')
->when('to_departments is not null and to_positions is null', function($query) use ($user){
$query->whereRaw('find_in_set('.$user->department.',to_departments)');
})
->when('to_positions is not null and to_department is null', function($query) use ($user){
$query->whereRaw('find_in_set('.$user->position.',to_positions)');
})
->orderBy('id','desc')
->get();
// with to_departments, to_positions is columns in table
您可以when
方法中使用laravel查詢構建器
DB::table('tasks')
->when($condition, function($query) use ($user){
$query->where('position', $user->position)
})
.....
->orderBy('id','desc')
->get();
當$condition
為true時,匿名函數將被執行。 它稱為條件條款
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.