我在互联网上搜索了我的问题,但我找不到答案。 我找到了关于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');
}
在 Controller :
中$data['lessons'] = Lesson::with(['student', 'teacher'])->first();
return var_dump($data['lessons']->student);
更新
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
}
]
谢谢你的帮助!
答案 0 :(得分:1)
如你所见,
#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');
}