【问题标题】:Laravel/SQL: where column Equals NOT and NULLLaravel/SQL:列等于 NOT 和 NULL
【发布时间】:2019-01-23 19:30:24
【问题描述】:

LARAVEL 5.4(但可能是更一般的 SQL 问题)

你好!我有一个结构表:

假设它是我的模型“表”。

我想要一个查询:

使用(接收)变量:

$id 的数组 ['id', 'string', integer]

其中字符串是 ''

$status_not_bad = bool;

(如果为 true - 包括 'status' !== 'bad' AND 'status' IS NULL 的所有行);

例如,我们给出:

$id = [['id', '>', 0]];

$status_not_bad = true;

Table::thisquery() ... ->get();

“获取状态不错且 id > 0 的行”返回第 1 行和第 3 行。

但如果我们给出:

$id = [['id', '<', 3]];

$status_not_bad = true;

Table::thisquery() ... ->get();

“获取状态不错且id

(应该是使用这些变量返回这些结果的相同查询)。

【问题讨论】:

    标签: sql laravel query-builder


    【解决方案1】:

    你可能会以这样的方式结束:

    if ($status_not_bad) {
        $nStatus = 'bad';
    } else {
        $nStatus = 'good';
    }
    
    Table::thisquery()->where('status', '<>', $nStatus)
                      ->whereNotNull('status')
                      ->where($id[0], $id[1], $id[2])
                      ->get();
    

    但最好先检查 $id 键。

    【讨论】:

    • 不起作用。如果 id > 0 ans $status_not_bad = true 它只返回第 1 行。但也应该返回第 3 行...
    • 此查询永远不会返回 NULL 行。返回 NULL 行的规则是什么?
    • 你能说得更具体些吗/
    • 我不明白什么时候必须返回或什么时候不能返回具有 NULL 状态的对象。
    【解决方案2】:

    由于行 id = 3 您需要在 where 语句中使用 &lt;= 才能将该行包含在结果集中

    $id = ['id', '<=', 3];
    

    【讨论】:

      【解决方案3】:

      所以,我这样做了:

      $chain = Sample::when($status_not_bad, function($query){
      
         return $query->where('status', '<>', 'bad')
                     ->orwhereNull('status');
      
      })
      
       ->where([$id])
       ->get();
      

      【讨论】:

        猜你喜欢
        • 2019-01-23
        • 2022-11-21
        • 1970-01-01
        • 2020-04-06
        • 2016-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多