简体   繁体   中英

How to check the column before executing the query in Laravel

Like the title of the question, I want to check a column in my table before executing the query in Laravel, such as checking if the "department" field is null then executing a query, if the positions "field" is null then executing a query. I want to check the column in the table is null, not data variable.

 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

you can use laravel query builder when method

DB::table('tasks')
  ->when($condition, function($query) use ($user){
         $query->where('position', $user->position)
     })
 .....
  ->orderBy('id','desc')
  ->get();

the anonymous function will get executed when the $condition is truthy. Its called Conditional Clauses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM