【问题标题】:How to check the column before executing the query in Laravel如何在 Laravel 中执行查询之前检查列
【发布时间】:2019-12-27 22:18:48
【问题描述】:

就像问题的标题一样,我想在 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

【问题讨论】:

标签: php mysql laravel where-clause laravel-query-builder


【解决方案1】:

你可以使用 laravel 查询生成器when 方法

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

$condition 为真时,匿名函数将被执行。 它叫Conditional Clauses

【讨论】:

  • 嗨 :( ,我是新手,所以很难理解,我试图将 $condition 替换为“部门为空”字符串(如果列为空),但它理解“部门为空” string = true 并且总是执行 你能再帮帮我吗?
  • 尝试发布您编写的代码示例,并附上确切的条件
  • 我更正了我的问题,重要的是如何在查询执行前检查空列
  • 我想你对我说的话感到困惑。实际上,$condition 不是 SQL 查询,而是 PHP 条件表达式。我们不知道您的表结构是什么样的,因此我们不知道to_departmentsto_positions 的外观如何,也不知道它们在哪个表中。也许您需要发布更多信息。
猜你喜欢
  • 1970-01-01
  • 2013-03-28
  • 2011-09-19
  • 2014-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 2014-01-07
相关资源
最近更新 更多