如何通过 laravel eloquent 模型 Laravel 5 加入三个表
Posted
技术标签:
【中文标题】如何通过 laravel eloquent 模型 Laravel 5 加入三个表【英文标题】:How to join three table by laravel eloquent model Laravel 5 【发布时间】:2016-01-20 17:22:53 【问题描述】:我在互联网上搜索了我的问题,但找不到答案。 我在*** 上找到了一个教程,但对于我的示例,它不起作用。
当我运行以下代码时,它返回NULL
:
$data['lessons']->student
我想得到什么:
ID |日期 |用户名 |老师的名字
我的代码:
我有 3 张桌子:
课程id、日期、fk_students_id、fk_teachers_id 学生 id, firstname 老师id, firstname模型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);
更新
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
]
感谢您的帮助!
【问题讨论】:
删除return var_dump($data['lessons']->student);
并放入dd($data);
,请发布结果
@AndreL 我已经更新了帖子。感谢您的帮助。
【参考方案1】:
如你所见,
#relations: array:2 [
"student" => null
"teacher" => 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');
【讨论】:
Laravel 能知道fk_students_id
是外键吗? laravel 知道这种模式吗?我总是声明local_key
's 和parent_key
's。只是问@Rudie。以上是关于如何通过 laravel eloquent 模型 Laravel 5 加入三个表的主要内容,如果未能解决你的问题,请参考以下文章
如何模拟 Laravel Eloquent 模型的静态方法?
如何在没有 Eloquent 的情况下创建 Laravel 模型?
Payum - Laravel 4 的包。如何使用 Eloquent 而不是 FilesystemStorage 创建模型数据?