simpson
simpson

Reputation: 77

Laravel retrieve relationship data via another relationship

I have three tables

Question table:

id
title
description

Answer table:

id
answerbody
question_id

Likes table:

id
answer_id

I want to retrieve single question details with all the answers and answer_count and their respective likes (only like_count)

I tried this

public function show($id)
{
    return question::with(['answers','answers.likes'])->withCount(['answers'])->where('id',$id)- 
    >get();
}

How do I return likes with count?

Upvotes: 1

Views: 82

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

If you need all answers for a question and along with their likes count you can call a closure inside your with() clause and load their related likes count as

Question::with(['answers'=> function ($query) {
                $query->withCount('likes')
                      ->orderBy('likes_count', 'desc');
        }])
        ->withCount(['answers'])
        ->where('id',$id)
        ->get();

This way you can also sort the answers based on their likes count

Upvotes: 1

smh_lotfizadeh
smh_lotfizadeh

Reputation: 31

Each question has many answers. So in the Question model add the below code :

public function answer()
    {
        return $this->hasMany(Answer::class);
    }

Each answer has many likes. So in the Answer model add the below code :

public function likes()
    {
        return $this->hasMany(Like::class);
    }

Now you have to define a mutator "getDataAttribute" as below in the Question model:

public function getDataAttribute()
    {
        return [
            'question' => $this,
            'answers' => $this->answers()->get(),
            'answer_count' => $this->answers()->get()->count(),
            'likes' => $this->answers()->likes()->get(),
        ];
    }

Finally, anywhere you needed the question information you just need to invoke :

$question->data

to retrieve question, likes and question count.

Upvotes: 0

Related Questions