【发布时间】:2018-10-17 00:56:55
【问题描述】:
我正在尝试在 Laravel 5.6 中建立 3 个模型之间的关系
这是我的桌子
部门
- 身份证
- 姓名
主题
- 身份证
- 姓名
教师
- 身份证
- 姓名
教
- id_teacher
- id_department
- id_subject
所有表之间的关系是多对多的。
老师可以在很多部门教很多科目
科属多学科
主题属于多个部门
如何在教师、部门和学科模型中建立这些关系?
【问题讨论】:
我正在尝试在 Laravel 5.6 中建立 3 个模型之间的关系
这是我的桌子
部门
主题
教师
教
所有表之间的关系是多对多的。
老师可以在很多部门教很多科目
科属多学科
主题属于多个部门
如何在教师、部门和学科模型中建立这些关系?
【问题讨论】:
你可以试试这样的:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
/**
* The teachs that belong to the department.
*/
public function teachs()
{
return $this->belongsToMany('App\Teach', 'teach_department', 'department_id', 'teach_id');
}
}
class Subject extends Model
{
/**
* The teachs that belong to the subject.
*/
public function teachs()
{
return $this->belongsToMany('App\Teach', 'teach_subject', 'subject_id', 'teach_id');
}
}
class Teacher extends Model
{
/**
* The teachs that belong to the teacher.
*/
public function teachs()
{
return $this->belongsToMany('App\Teach', 'teach_teacher', 'teacher_id', 'teach_id');
}
}
class Teach extends Model
{
/**
* The departments that belong to the teach.
*/
public function departments()
{
return $this->belongsToMany('App\Department', 'teach_department', 'teach_id', 'department_id');
}
/**
* The subjects that belong to the teach.
*/
public function subjects()
{
return $this->belongsToMany('App\Subject', 'teach_subject', 'teach_id', 'subject_id');
}
/**
* The teachers that belong to the teach.
*/
public function teachers()
{
return $this->belongsToMany('App\Teacher', 'teach_teacher', 'teach_id', 'teacher_id');
}
}
【讨论】: