1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
simpson
  • 67
  • 8

2 Answers2

1

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

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
  • @RaffianMoin If it worked give you your expected result please accept this answer or take a time to go through [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – M Khalid Junaid Feb 09 '21 at 09:18
0

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.