陈孝右 陈孝右 - 1 month ago 13
PHP Question

how to list all unanswerd questions use laravel model

I have 3 table which is

user_answer table==> id qid content
user_question table==> id title
user_question_count table=> id answer_num


UserAnswer Model:



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


UserQuestion Model



public function counts()
{
return $this->hasOne('App\Models\UserQuestionCount', 'id', 'id');
}


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


I want list all unanswered question use laravel relation model , unanswered question don't have record in UserQuestionCount table and UserAnswer table , how to realize this.

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

whereHas and doesntHave are made to check if a model has or doesn't have a relationship linked to it.

The documentation is available here if you scroll down a bit.

By the way, you should name your relationship answers and not answer since it's a One to Many.

Comments