1. 程式人生 > >Laravel5.2多級一對多的實現

Laravel5.2多級一對多的實現

例如一個學校,學校有許多年級,年級有許多班級,班級裡有許多老師,那麼這種多級的多對一該怎麼實現呢?

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';
   
}
2.控制器裡面查出
 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);
    }