Reputation: 185
I'm trying to make a relation between 3 Models in Laravel 5.6
Here are my tables
departments
subjects
teachers
teach
The relationship between all tables is many to many.
Teacher can teach many subjects in many department
department belongs to many subject
subject belongs to many department
How to make these relationships inside the Teacher, Department and Subject Models?
Upvotes: 4
Views: 621
Reputation: 1274
You can try something like this:
<?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');
}
}
Upvotes: 4