this is my tables look like
departments | course | subjects |
---|---|---|
id | id | id |
head | department_id | course_id |
course_name | subject_code |
My Answer:
To join 3 tables in Laravel using Eloquent relationships, you can use the `hasManyThrough` or `hasOneThrough` relationship methods.
In your case, you can define the relationships in your models as follows:
1. Department Model:
php
class Department extends Model
{
public function courses()
{
return $this->hasMany(Course::class, 'head_department_id');
}
}
2. Course Model:
php
class Course extends Model
{
public function subjects()
{
return $this->hasMany(Subject::class, 'course_id');
}
}
3. Subject Model:
php
class Subject extends Model
{
public function department()
{
return $this->hasOneThrough(Department::class, Course::class, 'head_department_id', 'id', 'course_id');
}
}
With these relationships defined, you can now access the department of a subject like this:
php
$subject = Subject::find($subjectId);
$department = $subject->department;
This will retrieve the department of the subject by joining the `departments`, `courses`, and `subjects` tables.
Rate this post
3 of 5 based on 6996 votesComments