dpv21589 2014-03-28 18:15
浏览 50
已采纳

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

I have the following tables:

lessons
- lessonID
- lessonName
..

sections
- sectionID
- lessonID references lessons.lessonID
..

exercises
- exerciseID
- sectionID references sections.sectionID
..

I have set up the following relations:

Lesson:

public function sections()
{
    return $this->hasMany('Section', 'lessonID');
}

Section:

public function lesson() {
    return $this->belongsTo('Lesson', 'lessonID');
}

public function exercise() {
    return $this->hasOne('Exercise', 'sectionID');
}

Exercise:

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

to the Lessons model and I run

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

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

Edit: 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,
        ...
        ));

    }
}

?>

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

And here are the query logs: http://laravel.io/bin/vebK

So in short: The Lesson and its Sections are returned fine, but I get an empty array for the Exercises.

  • 写回答

3条回答 默认 最新

  • doucaishou0074 2014-03-31 18:25
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度