简体   繁体   中英

How to join three table by laravel eloquent model Laravel 5

I searched on the internet for my problem but I couldn't find an answer. I found a tutorial on StackOverflow , but for my example it didn't worked.

When I run the following code, it returns NULL :

$data['lessons']->student

What i want to get:

ID | Date | User.firstname | Teacher.firstname

My code:

I have 3 Tables:

  • lesson {id, date, fk_students_id, fk_teachers_id}
  • student {id, firstname}
  • teacher{id, firstname}

Model Lesson.php :

public function student(){

    return $this->belongsTo('App\Student');
}

public  function teacher(){

    return $this->belongsTo('App\Teacher');
}

Model Student.php :

public function lessons(){
    return $this->hasMany('App\Lesson', 'fk_students_id');
}

Model Teacher.php :

public function lessons(){
    return $this->hasMany('App\Lesson', 'fk_teachers_id');
}

And in the Controller :

$data['lessons'] = Lesson::with(['student', 'teacher'])->first();
return var_dump($data['lessons']->student);

UPDATE Output of dd($data); :

array:1 [
"lessons" => Lesson {#303 
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:10 [
  "id" => 1
  "date" => "2015-07-25"
  "start" => "12:30:00"
  "end" => "13:00:00"
  "fk_students_id" => 1
  "fk_teachers_id" => 1
  "lesson_array" => "[{"id":"1", "result":"0"},{"id":"2", "result":"1"},{"id":"15", "result":"2"}]"
  "slug" => "562153eae355e"
  "created_at" => "0000-00-00 00:00:00"
  "updated_at" => "0000-00-00 00:00:00"
]
#original: array:10 [
  "id" => 1
  "date" => "2015-07-25"
  "start" => "12:30:00"
  "end" => "13:00:00"
  "fk_students_id" => 1
  "fk_teachers_id" => 1
  "lesson_array" => "[{"id":"1", "result":"0"},{"id":"2", "result":"1"},{"id":"15", "result":"2"}]"
  "slug" => "562153eae355e"
  "created_at" => "0000-00-00 00:00:00"
  "updated_at" => "0000-00-00 00:00:00"
]
#relations: array:2 [
  "student" => null
  "teacher" => null
]
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [
  0 => "*"
]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
]

Thank you for you help!

As you see,

#relations: array:2 [
  "student" => null
  "teacher" => null
] 

Are both null, is because of foreign keys name.

So you should set them on the model:

public function student(){

    return $this->belongsTo('App\Student', 'fk_teachers_id', 'id');
}

public  function teacher(){

    return $this->belongsTo('App\Teacher', 'fk_students_id','id');
}

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