Laravel 9中如何用Eloquent查询无关联答案的问题集合
解决方法
首先注意你的Answer模型关系写错了,因为是一对多关联,一个回答只能属于一个问题,所以应该用belongsTo而不是belongsToMany:
// Answer模型 public function question() { return $this->belongsTo(Question::class, 'ans_que_id'); }
接下来给你几种高效的Eloquent实现方式:
方法一:使用whereDoesntHave(推荐)
这是Laravel Eloquent专门为查询无关联模型设计的方法,代码简洁且性能最优:
public function notanswered() { // 返回没有任何回答的Question模型集合 return Question::whereDoesntHave('answers')->get(); // 如果只需要ID数组,和你原来的返回结果一致: // return Question::whereDoesntHave('answers')->pluck('id')->toArray(); }
whereDoesntHave会在数据库层面执行左连接并筛选无关联记录,避免了拉取所有问题再循环查询的低效操作。
方法二:使用withCount筛选
通过统计每个问题的回答数量,筛选出数量为0的问题:
public function notanswered() { // 返回模型集合 return Question::withCount('answers')->having('answers_count', 0)->get(); // 只返回ID数组: // return Question::withCount('answers')->having('answers_count', 0)->pluck('id')->toArray(); }
方法三:使用左连接(原生查询风格)
如果你习惯用连接查询的方式,也可以这样写:
public function notanswered() { return Question::leftJoin('answers', 'questions.id', '=', 'answers.ans_que_id') ->whereNull('answers.id') ->select('questions.*') ->distinct() ->get(); // 只返回ID数组: // return Question::leftJoin('answers', 'questions.id', '=', 'answers.ans_que_id') // ->whereNull('answers.id') // ->distinct() // ->pluck('questions.id') // ->toArray(); }
这些方法都比你原来的循环方式高效得多,因为所有筛选逻辑都在数据库层面完成,不需要加载所有问题到内存中再逐个判断。
内容的提问来源于stack exchange,提问作者Pouya Vaghefi
相关产品推荐
相关产品推荐

