如何列出所有未回答的问题使用 laravel 模型
how to list all unanswerd questions use laravel model
我有 3 个 table 是
user_answer table==> id qid content
user_question table==> id title
user_question_count table=> id answer_num
UserAnswer 模型:
public function question()
{
return $this->hasOne('App\Models\UserQuestion', 'id', 'qid');
}
用户问题模型
public function counts()
{
return $this->hasOne('App\Models\UserQuestionCount', 'id', 'id');
}
public function answer()
{
return $this->hasMany('App\Models\UserAnswer', 'qid', 'id');
}
我想列出所有未回答的问题使用 laravel 关系模型,未回答的问题在 UserQuestionCount table 和 UserAnswer table 中没有记录,如何实现这个。
$questions = UserQuestion::doesntHave('answer')->get();
whereHas
和 doesntHave
用于检查模型是否有或没有链接到它的关系。
如果您向下滚动一点,文档就可用 here。
顺便说一句,您应该将您的关系命名为 answers
而不是 answer
,因为它是一对多关系。
如果问题有很多答案,答案属于问题:
用户问题:
public function answers()
{
return $this->hasMany('App\Models\UserAnswer', 'qid', 'id');
}
用户回答:
public function question()
{
return $this->belongsTo('App\Models\UserQuestion','qid','id');
}
而您正在寻找 doesntHave。
那么,
$questions=UserQuestion::doesntHave('answers')->get();
我有 3 个 table 是
user_answer table==> id qid content
user_question table==> id title
user_question_count table=> id answer_num
UserAnswer 模型:
public function question()
{
return $this->hasOne('App\Models\UserQuestion', 'id', 'qid');
}
用户问题模型
public function counts()
{
return $this->hasOne('App\Models\UserQuestionCount', 'id', 'id');
}
public function answer()
{
return $this->hasMany('App\Models\UserAnswer', 'qid', 'id');
}
我想列出所有未回答的问题使用 laravel 关系模型,未回答的问题在 UserQuestionCount table 和 UserAnswer table 中没有记录,如何实现这个。
$questions = UserQuestion::doesntHave('answer')->get();
whereHas
和 doesntHave
用于检查模型是否有或没有链接到它的关系。
如果您向下滚动一点,文档就可用 here。
顺便说一句,您应该将您的关系命名为 answers
而不是 answer
,因为它是一对多关系。
如果问题有很多答案,答案属于问题:
用户问题:
public function answers()
{
return $this->hasMany('App\Models\UserAnswer', 'qid', 'id');
}
用户回答:
public function question()
{
return $this->belongsTo('App\Models\UserQuestion','qid','id');
}
而您正在寻找 doesntHave。 那么,
$questions=UserQuestion::doesntHave('answers')->get();