[英]Laravel Eloquent: How can I define this relationship?
我有以下表格:
lessons
- lessonID
- lessonName
..
sections
- sectionID
- lessonID references lessons.lessonID
..
exercises
- exerciseID
- sectionID references sections.sectionID
..
我建立了以下关系:
课:
public function sections()
{
return $this->hasMany('Section', 'lessonID');
}
部分:
public function lesson() {
return $this->belongsTo('Lesson', 'lessonID');
}
public function exercise() {
return $this->hasOne('Exercise', 'sectionID');
}
行使:
public function section() {
return $this->belongsTo('Section', 'sectionID');
}
现在我想说一个课程有很多练习通过章节,所以我尝试添加
public function exercises()
{
return $this->hasManyThrough('Exercise', 'Section', 'lessonID', 'sectionID');
}
到课程模型,我跑
Lesson::with('sections', 'exercises')
给我一个空阵列练习。 我怎样才能完成我想要的?
编辑:我正在播种练习表,如下所示:
<?php
class ExerciseTableSeeder extends Seeder {
public function run()
{
DB::table('exercises')->delete();
Exercise::create(array(
'exerciseID' => 1,
'sectionID' => 2,
...
));
Exercise::create(array(
'exerciseID' => 2,
'sectionID' => 4,
...
));
}
}
?>
编辑2:这是我的模型: http : //laravel.io/bin/2Rdl
以下是查询日志: http : //laravel.io/bin/vebK
简而言之: Lesson及其Sections返回正常,但我得到一个空数组练习。
我在他们的Github上报告了这个问题后,我得到了一个令人尴尬的简单答案:请求应该是Lesson::with('sections.exercises')
。
这就是问题所在:
public function exercise() {
return $this->hasOne('Exercise', 'Section');
}
应该:
public function exercise() {
return $this->hasOne('Exercise', 'sectionID');
}
编辑:
您的hasManyThrough关系也是错误的。 它是这样的:
hasManyThrough('farModel', 'relatedModel', 'keyOnRelatedModel', 'keyOnFarModel')
如此正确:
public function exercises()
{
return $this->hasManyThrough('Exercise', 'Section', 'lessonID', 'sectionID');
}
编辑:到@clod986注意 - hasManyThrough()对于ONE-TO-MANY也是一样的 - > ONE-TO-ONE,只要后者是hasOne(不是belongsTo)关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.