繁体   English   中英

Laravel Eloquent:我如何定义这种关系?

[英]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')

在@ deczo的帮助之后,现在设置它对我来说似乎很好。 Probalby你只是没有任何相关的条目,这可能是一个空阵列的原因

编辑

似乎在这种情况下不应该使用hasManyThrough函数。

鉴于关系设置正确(正如您在对此答案的评论中所确认的),答案可以在文档中找到。 它明确指出

例如,一个国家的模型可能需要通过用户模型很多帖子

我相信hasManyThrough的关系是针对hasManyThrough + hasManyThrough 在你的情况下是一对多+一对一,这可能是它不起作用的原因。

我建议你把这个问题报告给github页面

这就是问题所在:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM