Laravel whereNotExists 关系

Laravel whereNotExists relation

我在数据库中有几个 table。 我尝试在 QuizSubmissionController 中创建关系以获取尚未回答提交的问题。 我可以写类似 $quiz_submission->quiz->questions()->whereDoesntHave('answers')whereNotExist('submission_answers') 的东西吗?

我这里的亲戚:

// Quiz Class
public function category()
{
    return $this->belongsTo(Category::class);
}
public function questions()
{
    return $this->hasMany(Question::class);
}

// Question Class
public function quiz()
{
    return $this->belongsTo(Quiz::class);
}
public function category()
{
    return $this->hasOneThrough(Category::class, Quiz::class);
}
public function answers()
{
    return $this->hasMany(Answer::class,
        'question_id'
    );
}
// Answer Class
public function question()
{
    return $this->belongsTo(Question::class);
}
// QuizSubmission Class
public function user()
{
    return $this->belongsTo(User::class);
}
/**
 * @return BelongsTo
 */
public function quiz()
{
    return $this->belongsTo(Quiz::class);
}
/**
 * @return HasMany
 */
public function questions()
{
    return $this->quiz()->whereNotExists()->questions();
}
public function submission_answers()
{
    return $this->hasMany(SubmissionAnswer::class);
}
public function getUnansweredQuestions()
{
    return $this->submission_answers()->doesntHave('answers');
}
// SubmissionAnswer Class
public function answers()
{
    return $this->hasMany(Answer::class);
}

如何 getUnansweredQuestions 获取 submission_answer table 中没有的所有问题?这是可能的还是我需要编写原始数据库查询?

我也有想法插入所有带有问题 ID 的行而没有答案,然后得到所有 submission_answers 其中 answer_idnull

Laravel 中,您可以调整关系以包含条件,而不是像您尝试的那样尝试更改结果。创建两个关系,一个包含所有答案,另一个包含条件。

LaraveldoesntHave()orDoesntHave(),对于你试图实现的这个逻辑。如果你想要这个逻辑,在 SQL 条件下,你可以使用 whereDoesntHave() 将带有查询构建器的闭包作为输入。

public function unansweredQuestions()
{
   return $this->hasMany(SubmissionAnswer::class)->doesntHave('answers');
}

要获取的示例 unansweredQuestions

$quizSubmission::find(42)->unansweredQuestions;

奖金,我认为干净的代码或高质量是一致性。将 submission_answers 用作关系名称与命名约定不一致。应该是 public 函数 submissionAnswers().