Laravel关联查询:通过hasMany与belongsToMany多级关联获取教师名下学生
Laravel 多级关联查询指定教师对应的学生实现方案
前置条件:先完成基础模型关联
在三个对应的模型中分别声明基础关联:
1. Teacher 模型(app/Models/Teacher.php)
定义和课时(periods)的一对多关联:
public function periods() { return $this->hasMany(Period::class); }
2. Period 模型(app/Models/Period.php)
分别定义和教师的从属关联、和学生的多对多关联:
public function teacher() { return $this->belongsTo(Teacher::class); } public function students() { return $this->belongsToMany(Student::class, 'student_period'); }
3. Student 模型(app/Models/Student.php)
定义和课时的多对多关联:
public function periods() { return $this->belongsToMany(Period::class, 'student_period'); }
具体查询实现
方式1:单次临时查询(无需额外定义关联)
直接通过whereHas嵌套关联条件查询,适合偶尔调用的场景:
// $teacherId 为指定要查询的教师ID $students = Student::whereHas('periods', function ($query) use ($teacherId) { $query->where('teacher_id', $teacherId); })->distinct()->get();
加distinct()是为了避免同一个学生选修了该教师的多个课时时出现重复数据。
方式2:关联预加载+结果处理
如果需要同时获取教师信息、对应课时、对应学生,用预加载的方式性能更高:
// 先查询教师并预加载关联的课时、课时关联的学生 $teacher = Teacher::with('periods.students')->find($teacherId); // 从所有课时中提取学生并去重 $students = $teacher->periods->pluck('students')->flatten()->unique('id');
方式3:定义可复用的关联方法(适合高频调用场景)
如果需要频繁查询教师对应的学生,可在Teacher模型中封装自定义关联方法,后续直接调用即可:
在Teacher.php中新增方法:
public function students() { return Student::whereHas('periods', function ($query) { $query->where('teacher_id', $this->id); })->distinct(); }
调用时直接使用:
$teacher = Teacher::find($teacherId); $students = $teacher->students()->get();
内容的提问来源于stack exchange,提问作者nhnkl122
相关产品推荐
相关产品推荐

