多个 where 子句,Laravel

Multiple where clause, Laravel

我尝试使用 2 个 where 子句进行查询,但得到了错误的响应,不知道为什么。

$history = AnswerHistory::where('question_id', '=', $id)
     ->where(function ($query) {
            $query->where('answer_type', '!=', "skipped");
      })
      ->get();

对于数据库中的特定 $id,我有 5 行,其中 4 行带有 answer_type = 'skipped,但第 5 行是 NULL

我对这段代码的回复是空的,如果我删除第二个,我得到 5 个项目,其中包括 "skipped" 个答案。

需要的响应是 1 行,其中 answer_type != 'skipped'

PS。我也尝试了 here.

的答案

您可以像这样更改多个 where 条件的查询

$history = AnswerHistory::where([['question_id', '=', $id],['answer_type','<>','skipped']])
                        ->get()
                        ->toArray();

并将!=替换为<>

希望对您有所帮助

问题是,null 的 varchar 是 null 而不是具有值的 varchar。所以不能用=!='string'来检查。所以你必须检查 answer_type 是 != skipped 还是 null

$history = AnswerHistory::where('question_id', '=', $id)
    ->where(function ($query) {
        $query->where('answer_type', '!=', "skipped")
            ->orWhereNull('answer_type');
    })
    ->get();