I’m working on a forum project using Laravel 9 and I have added a custom filter for loading the questions that have not any answer yet.
And also there’s a One To Many relationship between Question Model & Answer Model:
Question
:
public function answers()
{
return $this->hasMany(Answer::class,'ans_que_id');
}
Answer
:
public function questions()
{
return $this->belongsToMany(Question::class);
}
So in order to return the list of questions that do not have any submitted answers, I tried this (without using Eloquent):
public function notanswered()
{
$questions = Question::all();
$questions_with_no_answer = [];
foreach($questions as $question){
$answer = Answer::where('ans_que_id',$question->id)->first();
if(!$answer){
array_push($questions_with_no_answer,$question->id);
}else{
continue;
}
}
return $questions_with_no_answer;
}
And this is basically correct but I don’t want to do this within the pure way and I need an Eloquent way to do the same thing.
But I don’t know how to do that in this situation, so if you know, please let me know.
3
Answers
use Querying Relationship Absence
As per Laravel official documentation
In Your Question Model First define the scope of notAnswered in this scope first fetch the ans_que_id from Answer Model and pass this question ids in whereNotIn function of laravel.
So you can use this:
You can use Eloquent to achieve this by utilizing a subquery to filter out the questions that have answers.
Here’s how you can do it:
The whereDoesntHave method is used to filter out the questions that have answers. It takes the name of the relationship (answers in this case) as its argument.
The pluck method is used to retrieve only the id column of the questions that meet the condition.
Finally, toArray is called to convert the result to an array.
This code will return an array of ids of the questions that do not have any answers.