英文:
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论