例如一个学校,学校有许多年级,年级有许多班级,班级里有许多老师,那么这种多级的多对一该怎么实现呢?
1.先设置他们的Model
学校的: School.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class schoolClass extends Model
{
protected $table = 'schools';
public function hasManyGrades(
{
return $this->hasMany('App\Grade', 'school_id', 'id');
}
}
年级的:Grade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Grade extends Model
{
protected $table = 'grades';
public function hasManyClasses()
{
return $this->hasMany('App\schoolClass', 'grade_id', 'id');
}
}
班级的:schoolSchool.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class schoolClass extends Model
{
protected $table = 'jjxiao_classes';
public function hasManyTeachers()
{
return $this->hasMany('App\Teacher', 'class_id', 'id');
}
}
老师的:Teacher.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
protected $table = 'jjxiao_teacher_staffs';
}
public function index(){
$id=1;
$school=School::find($id);
$grades=$school->hasManyGrades()->get();//找到所有的年级
foreach($grades as $g){
$classes[]=$g->hasManyClasses()->get(); //每个年级找到所对应的班级
}
foreach ($classes as $cl) {
foreach($cl as $c){
$teachers[]=$c->hasManyTeachers()->get(); //每个班级找到老师
}
}
foreach ($teachers as $te) { //给数组脱维
foreach($te as $t){
$teacher[]=$t;
}
}
return view('home.myschool_teacher.index')
->withGrade($grades)
->withTeacher($teacher);
}