我有以下表格:
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
简而言之:课程及其章节返回正常,但我为练习获得了一个空数组。
答案 0 :(得分:3)
在their Github上报告问题后,我得到了一个令人尴尬的简单回答:请求应该是Lesson::with('sections.exercises')
。
答案 1 :(得分:2)
在@ deczo的帮助之后,现在设置它似乎很好。 Probalby你没有任何相关的条目,这可能是一个空数组的原因
修改强>
似乎在这种情况下不应该使用hasManyThrough
函数。
鉴于关系设置正确(正如您在对此答案的评论中所确认),答案可以在documentation中找到。它明确指出
例如,国家/地区模型可能通过 a 用户拥有多个帖子 模型
我认为hasManyThrough
的关系是针对一对一+一对多的关系。在你的情况下是一对多+一对一,这可能是它无法工作的原因。
我建议您将此问题报告给github page。
答案 2 :(得分:1)
问题在于:
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');
}
编辑: to @clod986 note - hasManyThrough()对于ONE-TO-MANY也是一样的 - &gt;一对一,只要后者是hasOne(非belongsTo)关系。