[英]How to join three table by laravel eloquent model Laravel 5
我在互聯網上搜索了自己的問題,但找不到答案。 我在StackOverflow上找到了一個教程,但是對於我的示例卻沒有用。
當我運行以下代碼時,它返回NULL
:
$data['lessons']->student
我想得到什么:
ID | 日期| User.firstname | Teacher.firstname
我的代碼:
我有3張桌子:
模型Lesson.php :
public function student(){
return $this->belongsTo('App\Student');
}
public function teacher(){
return $this->belongsTo('App\Teacher');
}
模型Student.php :
public function lessons(){
return $this->hasMany('App\Lesson', 'fk_students_id');
}
模型Teacher.php :
public function lessons(){
return $this->hasMany('App\Lesson', 'fk_teachers_id');
}
在控制器中 :
$data['lessons'] = Lesson::with(['student', 'teacher'])->first();
return var_dump($data['lessons']->student);
UPDATE 輸出 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
}
]
謝謝你的幫助!
正如你看到的,
#relations: array:2 [
"student" => null
"teacher" => null
]
兩者均為null,是因為有外鍵名稱。
因此,您應該在模型上設置它們:
public function student(){
return $this->belongsTo('App\Student', 'fk_teachers_id', 'id');
}
public function teacher(){
return $this->belongsTo('App\Teacher', 'fk_students_id','id');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.