Laravel雄辩:我如何界定这种关系? [英] Laravel Eloquent: How can I define this relationship?

查看:117
本文介绍了Laravel雄辩:我如何界定这种关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下表格:

lessons
- lessonID
- lessonName
..

sections
- sectionID
- lessonID references lessons.lessonID
..

exercises
- exerciseID
- sectionID references sections.sectionID
..

我已经设置了以下关系:

I have set up the following relations:

课程:

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');
}

现在我想说一节课有很多练习通过章节,所以我尝试添加

Now I want to say that a Lesson has many Exercises through Sections, so I tried adding

public function exercises()
{
    return $this->hasManyThrough('Exercise', 'Section', 'lessonID', 'sectionID');
}

到课程模型,我运行

Lesson :: with('sections','exercise')

给我一​​个空阵列练习。如何完成我想要的?

gives me an empty array for the exercises. How can I accomplish what I want?

编辑:我正在播放练习表:

I'm seeding the Exercise table like so:

<?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

Edit 2: Here's my models: http://laravel.io/bin/2Rdl

这里是查询日志: http://laravel.io/bin/vebK

所以简而言之:课程及其部分返回正常,但我将为练习获得一个空数组。

推荐答案

他们的Github 报告问题后,我得到了一个令人尴尬的简单答案:请求应该是 Lesson :: with('sections.exercises')

After I reported the issue on their Github, I got an embarrassingly simple answer: the request should be Lesson::with('sections.exercises') instead.

这篇关于Laravel雄辩:我如何界定这种关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆