Reputation: 185
I have a relationship between these 3 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');
}
}
I want to list all departments and subjects of a specific teacher using these relation I've tried this in my view but it doesn't work $teacher->teach->departments;
Upvotes: 0
Views: 40
Reputation: 8287
This is the Many to Many relationship between teacher and 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');
}
}
Now fetch data
$teacher = Teacher::with('departments')->find(1);
$departments = $teacher->departments;
Upvotes: 1