简体   繁体   中英

hasManyThrough - Laravel 5.8

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('App\ClassCourseTeacher', '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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM