1

I'm working on a forum project using Laravel 9 and for this project, there is a One To Many relationship between Question & Answer:

Question.php Model:

public function answers()
    {
        return $this->hasMany(Answer::class,'ans_que_id');
    }

And this is for Answer Model:

public function questions()
    {
        return $this->belongsToMany(Question::class);
    }

Now I want to get the questions that has the most answers.

But I don't know how to do that, so if you know, please let me know...

Thanks.

Pouya
  • 114
  • 1
  • 8
  • 36

1 Answers1

1

You can use withCount()(Documentation) then sort by them

example:

Question::query()->withCount('answers')->orderByDesc('answers_count')->get();
A.Seddighi
  • 1,695
  • 1
  • 20
  • 43