Search code examples
phplaravellaravel-9eloquent-relationshiplaravel-relations

How to get the collection of rows that their HAS MANY relationship is empty


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.


Solution

  • use Querying Relationship Absence

    Question::doesntHave('answers')->get()
    

    As per Laravel official documentation

    When retrieving model records, you may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that don't have any comments. To do so, you may pass the name of the relationship to the doesntHave and orDoesntHave methods:

    use App\Models\Post;
     
    $posts = Post::doesntHave('comments')->get();