You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取筛选后所有学生关联的全部Teacher模型(分页场景)

问题描述

假设有两个关联模型Student和Teacher,其中Student隶属于Teacher。当前控制器的index方法返回带分页和筛选条件的所有学生:

return new StudentCollection(
   Student::with('teacher')->where('age', 25)->paginate()
);

自定义的StudentCollection如下:

public function toArray($request)
{
    return [
        'data' => $this->collection,
        'teachers' => [], // 此处需填充
    ];
}

需求是获取筛选后所有学生对应的全部关联Teacher,但因查询已分页,无法直接对当前页集合使用pluck,需要获取所有符合筛选条件的学生的关联Teacher而非单页的,该如何实现?

解决方案

可以通过以下两种实用方式实现:

方法一:复用筛选条件查询所有关联教师

先提取筛选逻辑,单独查询符合条件的学生对应的教师,避免重复编写筛选规则:

  1. 控制器中拆分查询逻辑:
// 先构建筛选学生的查询实例
$studentQuery = Student::where('age', 25);
// 执行分页查询,同时预加载教师关联
$students = $studentQuery->with('teacher')->paginate();
// 提取所有符合条件学生的教师ID并去重,再查询对应的教师
$teacherIds = $studentQuery->pluck('teacher_id')->unique();
$teachers = Teacher::whereIn('id', $teacherIds)->get();
// 将教师集合传入自定义资源集合
return new StudentCollection($students, $teachers);
  1. 修改StudentCollection接收教师参数:
protected $teachers;

public function __construct($resource, $teachers)
{
    parent::__construct($resource);
    $this->teachers = $teachers;
}

public function toArray($request)
{
    return [
        'data' => $this->collection,
        'teachers' => $this->teachers,
    ];
}

方法二:用whereHas直接筛选关联教师

利用Eloquent的whereHas方法,直接筛选出拥有符合条件学生的教师,代码更简洁:

// 直接查询所有关联了年龄25岁学生的教师
$teachers = Teacher::whereHas('students', function($query) {
    $query->where('age', 25);
})->get();
// 执行学生分页查询
$students = Student::with('teacher')->where('age', 25)->paginate();
// 传入自定义集合返回
return new StudentCollection($students, $teachers);

注意事项

  • 两种方法都能获取所有符合筛选条件的学生对应的教师,而非仅当前分页的教师;
  • 方法一适合筛选条件复杂的场景,复用查询逻辑可避免重复代码;
  • 方法二更适合关联关系清晰的场景,执行效率更高。

内容的提问来源于stack exchange,提问作者norr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 03:12:41