例如一个学校,学校有许多年级,年级有许多班级,班级里有许多老师,那么这种多级的多对一该怎么实现呢?
1.先设置他们的Model
学校的: School.PHP
[php]view plain
copy print ?
- 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]view plain copy print ?
- 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]view plain copy print ?
- 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]view plain copy print ?
- namespace App;
- use Illuminate\Database\Eloquent\Model;
- class Teacher extends Model
- {
- protected $table = 'jjxiao_teacher_staffs';
- }
2.控制器里面查出 【Laravel5 关联查询 —— 多级一对多的实现】
[php]view plain copy print ?
- 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);
- }
推荐阅读
- laravel 8 修改默认的paginate分页模板
- laravel|国际支付对接,信用卡支付对接,stripe的使用
- laravel|laravel执行过程
- 搭建远程GIT
- Laravel 自带的Auth验证登录
- php|lnmp搭建遇到的尴尬事(一)
- Laravel mysql 添加外键失败
- php|laravel attempt登陆认证时候帐号密码输入正确但返回false的情况
- Laravel|laravel 验证大于零的数字
- laravel|Composer 本地路径加载 laravel-admin 扩展包