I have database table structure like :
ClassRoom
- id (int) PK
- name (varchar)
ClassTeacherCourse
- id (int) PK
- id_classroom (int) FK
- id_teacher (int) FK
- id_course (int) FK
Course
- id (int) PK
- course_name (varchar)
Teacher
- id (int) PK
- teacher_name (varchar)
So far I have code just to call ClassRoom table & ClassTeacherCourse, like :
$class = Class::find($id) ->with(['classcourseteacher']) ->get();
Relationship in Class
Model :
public function classcourseteacher() { return $this->hasMany('AppClassCourseTeacher', 'id_class', 'id'); }
Result :
[ { "id": 57, "id_school": 2, "class_name": "7 I", "classcourseteacher": [ { "id": 406, "id_class": 57, "id_course": 9, "id_teacher": 68, "created_at": "2020-11-10 16:11:14", "updated_at": "2020-11-10 16:11:14" }, { "id": 434, "id_class": 57, "id_course": 11, "id_teacher": 66, "created_at": "2020-11-10 16:11:14", "updated_at": "2020-11-10 16:11:14" }, ] } ]
I have read Eloquent: Relationships about hasManyThrough
but in docs different case with me.
How to call in 1 time via Eloquent: Relationship with Course & Teacher details?
Advertisement
Answer
in ClassTeacherCourse
class put the teacher and course relation
function teacher() { return $this->belongsTo(Teacher::class); } function course() { return $this->belongsTo(Course::class); }
and then u can call it like this to get the detail
$class = Class::find($id) ->with(['classcourseteacher.teacher', 'classcourseteacher.course']) ->get();