Laravel 11.x中如何通过Eloquent关联直接获取指定Curriculum对应的Student集合(四层表关联场景)
Laravel 11.x中如何通过Eloquent关联直接获取指定Curriculum对应的Student集合(四层表关联场景)
嗨,我完全理解你的需求——你现在想从Curriculum模型直接拿到关联的学生集合,而不是先拿到课程再嵌套学生,对吧?这其实在Eloquent里有几种优雅的实现方式,我给你拆解一下:
首先得确认你已经在Course模型里定义了和Student的多对多关联,应该是这样的:
// Course模型 public function students() { return $this->belongsToMany(Student::class, 'students_courses'); }
接下来回到Curriculum模型,这里有两种实用方法:
方法一:使用关联查询构造器(简洁灵活)
在Curriculum模型里定义一个students()方法,通过whereHas来关联过滤,这样能直接定位到属于当前课程体系的学生:
// Curriculum模型 public function students() { return Student::whereHas('courses', function ($query) { $query->where('curriculum_id', $this->id); }); }
使用的时候直接调用$curriculum->students()->get()就能拿到纯净的Student集合,而且还能继续链式追加其他查询条件,比如$curriculum->students()->where('age', '>', 18)->get(),适配各种业务场景。
方法二:自定义Eloquent关联(ORM原生风格)
如果你想让它像原生Eloquent关联一样,直接用$curriculum->students获取集合(不需要额外加get()),可以结合belongsToMany和多表关联来实现:
// Curriculum模型 public function students() { return $this->belongsToMany(Student::class) ->join('students_courses', 'students.id', '=', 'students_courses.student_id') ->join('courses', 'students_courses.course_id', '=', 'courses.id') ->whereColumn('courses.curriculum_id', '=', $this->getKey()) ->select('students.*') ->distinct(); // 去重,避免同一个学生选了多个同课程体系的课程导致重复 }
这样你就可以像调用普通关联一样,直接用$curriculum->students拿到目标学生集合,完全贴合Eloquent的使用习惯。
额外优化技巧:预加载避免N+1问题
如果你经常需要同时获取课程体系和对应的学生,可以在查询Curriculum时直接预加载这个关联,提升查询效率:
$curriculum = Curriculum::with('students')->find($id); $students = $curriculum->students;
备注:内容来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

