如何通过 Eloquent 关系获取具有最多答案的主题。

huangapple go评论69阅读模式
英文:

How to get the topics that have most answers by Eloquent Relationship

问题

我想获取拥有最多答案的问题。

英文:

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.

答案1

得分: 1

你可以使用withCount()文档)来进行计数,然后按它们进行排序。

示例:

Question::query()->withCount('answers')->orderByDesc('answers_count')->get();
英文:

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

example:

Question::query()->withCount('answers')->orderByDesc('answers_count')->get();

huangapple
  • 本文由 发表于 2023年2月27日 12:40:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定