this is my tables look like
| departments | course | subjects |
|---|---|---|
| id | id | id |
| head | department_id | course_id |
| course_name | subject_code |
in my models this is how I do it but seems not working and I don't know why:
public function departments()
{
return $this->hasOneThrough(
subjectlist::class,
department::class,
'id',
'course_id',
'id',
'id'
);
}
The output when I try to use hasOneThrough:
{
"id": 1,
"department_name": "Business",
"head": "John smith",
"email": "smith@gmail.com",
"contact_number": "09300282103",
"created_at": null,
"updated_at": null,
"subject_list": {
"id": 1,
"course_id": 1,
"subject_code": "Math1",
"description": "math test",
"year_type": 1,
"price": "200.00",
"units": "5.00",
"created_at": null,
"updated_at": null,
"laravel_through_key": 1
}
}
I wan't the output should be like this please help me how to do it:
{
"id": 1,
"department_name": "Business",
"head": "John smith",
"email": "smith@gmail.com",
"contact_number": "09300282103",
"created_at": null,
"updated_at": null,
"subject_list": {
"id": 1,
"course_id": 1,
"subject_code": "Math1",
"description": "math test",
"year_type": 1,
"price": "200.00",
"units": "5.00",
"created_at": null,
"updated_at": null,
"laravel_through_key": 1
},
"department": {
"id": 1,
"department_name": "ComputerScience"
}
}
Relationship between your tables are like Subject as a Course Course has a Department and Subject has a department through course
Relation For Your Subject Model
public function Course() {
return $this->belongsTo(Course::class);
}
public function Department() {
return $this->hasOneThrough(Department::class, Course::class)
}
Relation For Your Course Model
public function Subject() {
return $this->hasMany(Subject::class);
}
public function Department() {
return $this->belongsTo(Department::class);
}
Relation For Your Department Model
public function Course() {
return $this->hasMany(Course::class);
}
For farther info refer to laravel eloquent relationships documentation https://laravel.com/docs/8.x/eloquent-relationships#has-one-through