[英]Laravel blade relationships using models
我在这三个模型之间有关系
class Teach extends Model {
public function departments() {
return $this->belongsToMany('App\Department', 'teach', 'id', 'department_id');
}
public function subjects() {
return $this->belongsToMany('App\Subject', 'teach', 'id', 'subject_id');
}
public function teachers() {
return $this->belongsToMany('App\Teacher', 'teach', 'id', 'teacher_id');
}
}
我想使用这些关系列出特定教师的所有部门和科目,我曾尝试过此方法,但它不起作用$ teacher-> teach-> departments;
这是教师与部门之间的多对多关系
class Teacher extends Model {
public function departments() {
return $this->belongsToMany('App\Department', 'teach', 'teacher_id', 'department_id');
}
}
class Department extends Model {
public function teachers() {
return $this->belongsToMany('App\Teacher', 'teach', 'department_id', 'teacher_id');
}
}
现在获取数据
$teacher = Teacher::with('departments')->find(1);
$departments = $teacher->departments;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.