Laravel5 关联查询 —— 多级一对多的实现

例如一个学校,学校有许多年级,年级有许多班级,班级里有许多老师,那么这种多级的多对一该怎么实现呢?
1.先设置他们的Model
学校的: School.PHP

[php]view plain copy print ?

  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class schoolClass extends Model
  4. {
  5. protected $table = 'schools';
  6. public function hasManyGrades(
  7. {
  8. return $this->hasMany('App\Grade', 'school_id', 'id');
  9. }
  10. }


年级的:Grade.php

[php]view plain copy print ?
  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class Grade extends Model
  4. {
  5. protected $table = 'grades';
  6. public function hasManyClasses()
  7. {
  8. return $this->hasMany('App\schoolClass', 'grade_id', 'id');
  9. }
  10. }



班级的:schoolSchool.php

[php]view plain copy print ?
  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class schoolClass extends Model
  4. {
  5. protected $table = 'jjxiao_classes';
  6. public function hasManyTeachers()
  7. {
  8. return $this->hasMany('App\Teacher', 'class_id', 'id');
  9. }
  10. }



老师的:Teacher.php

[php]view plain copy print ?
  1. namespace App;
  2. use Illuminate\Database\Eloquent\Model;
  3. class Teacher extends Model
  4. {
  5. protected $table = 'jjxiao_teacher_staffs';
  6. }



2.控制器里面查出 【Laravel5 关联查询 —— 多级一对多的实现】
[php]view plain copy print ?
  1. public function index(){
  2. $id=1;
  3. $school=School::find($id);
  4. $grades=$school->hasManyGrades()->get(); //找到所有的年级
  5. foreach($grades as $g){
  6. $classes[]=$g->hasManyClasses()->get(); //每个年级找到所对应的班级
  7. }
  8. foreach ($classes as $cl) {
  9. foreach($cl as $c){
  10. $teachers[]=$c->hasManyTeachers()->get(); //每个班级找到老师
  11. }
  12. }
  13. foreach ($teachers as $te) {//给数组脱维
  14. foreach($te as $t){
  15. $teacher[]=$t;
  16. }
  17. }
  18. return view('home.myschool_teacher.index')
  19. ->withGrade($grades)
  20. ->withTeacher($teacher);
  21. }

    推荐阅读