【问题标题】:Check if a column is null in relationship, Laravel检查列是否在关系中为空,Laravel
【发布时间】:2020-05-25 15:21:16
【问题描述】:

我尝试检查关系表中的列是否为空,.但是使用我当前的代码,我得到一个错误。 第二个whereNotNull中的列是"best_match"

SQLSTATE[42P01]:未定义表:7 错误:缺少 FROM 子句条目 对于表“问题”↵LINE 1:

$questions = Model::whereNotNull('question_id');

if($excepted_questions){
   $questions->whereNotIn('id', $excepted_questions);
}

$questions->where('votes', '!=' , $confidence_specs->votes)
   ->orWhere('weight', '!=' , $confidence_specs->weight)
   ->with('questions')
   ->inRandomOrder();

//HERE I try to check if that column is null or not
if($confidence_specs->best_match){ // this can be true / false ,if is true I check if that column is null
   $questions->whereNotNull('questions.best_match');
}

$questions->limit($nr_of_questions)
   ->get();

【问题讨论】:

  • 使用 $questions = Question::whereNotNull('question_id');
  • 请再次阅读说明。问题来自代码中的第二个 whereNotNull。
  • 转储 $questions->toSql() 并查看查询内容。
  • 给出 $questions->whereNotNull('best_match');并尝试
  • 我更新了问题。看起来就是这样,但我不使用 whereNotNull 进行 best_match。

标签: laravel laravel-7


【解决方案1】:

您必须使用whereHas 才能将where 语句与关系模型一起使用,否则您必须已加入表。

否则仅使用where 语句将无法在多个表上工作。

有关更多信息,请查看文档Querying Relationship Existence

所以你的查询应该是

if($confidence_specs->best_match){ 
   $questions->whereHas('questions', function($query){
       $query->whereNotNull('best_match);
    })
}

with 只会急切地加载模型,它不允许您对其执行 MySQL 查询。

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 1970-01-01
    • 2020-02-04
    • 2017-09-14
    • 2020-06-21
    • 2015-06-14
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    相关资源
    最近更新 更多