如何通过Eloquent关联获取回答数最多的问题(Laravel 9)
解决Laravel 9中获取回答数最多的问题的方法
首先先修正你的关联模型错误:
因为Question和Answer是一对多关联,所以Answer模型中的关联方法应该使用belongsTo而非belongsToMany,修改后的Answer模型代码如下:
public function question() { return $this->belongsTo(Question::class, 'ans_que_id'); }
接下来提供几种获取回答数最多的问题的实现方式:
方式一:使用withCount和排序(推荐)
通过withCount统计每个问题的回答数量,再按回答数倒序排序,即可拿到目标数据:
获取单个回答最多的问题
$mostAnsweredQuestion = Question::withCount('answers') ->orderBy('answers_count', 'desc') ->first();
获取前N个回答最多的问题(示例为前5个)
$topQuestions = Question::withCount('answers') ->orderBy('answers_count', 'desc') ->take(5) ->get();
方式二:使用分组查询
通过原生SQL分组统计,再关联到Question模型:
$mostAnsweredQuestion = Question::select('questions.*', DB::raw('count(answers.id) as answers_count')) ->leftJoin('answers', 'questions.id', '=', 'answers.ans_que_id') ->groupBy('questions.id') ->orderBy('answers_count', 'desc') ->first();
补充说明:
withCount是Laravel提供的便捷方法,会自动为查询结果添加answers_count字段,性能和可读性都更优- 如果需要排除无回答的问题,可在
withCount后追加where('answers_count', '>', 0),或把leftJoin替换为join
内容的提问来源于stack exchange,提问作者Pouya Vaghefi
相关产品推荐
相关产品推荐

