繁体   English   中英

在Laravel中执行查询之前如何检查列

[英]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.

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