如何使用laravel模型列出所有未回答的问题


how to list all unanswerd questions use laravel model

我有3个表,它是

  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表和UserAnswer表中没有记录,如何实现这一点。

$questions = UserQuestion::doesntHave('answer')->get();

whereHasdoesntHave用于检查模型是否有关联关系。

如果您向下滚动一点,文档就可以在这里找到。

顺便说一句,你应该把你的关系命名为answers,而不是answer,因为这是一对多的关系。

如果问题有许多答案,请回答以下问题:

用户问题:

 public function answers()
 {
      return $this->hasMany('App'Models'UserAnswer', 'qid', 'id');
 }

用户答案:

   public function question()
    {
        return $this->belongsTo('App'Models'UserQuestion','qid','id'); 
    }

而你正在寻找的是dontHave。然后,

$questions=UserQuestion::doesntHave('answers')->get();