我想从三个表中检索数据:类(class),能力和功能标准。以下查询几乎可以使用,但不会带回关联的competency_standards表数据。

    $coursesAndComps = Course::with(
        array('competencies' => function($query)
        {
            Competency::with('competency_standards');
        })
    )->get()->toArray();

其中competencies表链接到courses表(competencies.course_id = course.id),而competency_standards表链接到competencies表(competency_standards.competencey_id = capability.id)。

返回的数组如下所示:
Array
(
[0] => Array
    (
        [id] => 1
        [name] => the first course
        [competencies] => Array
        (
            [0] => Array
            (
                [id] => 9
                [course_id] => 1
                [name] => first course comp 1
            )

            [1] => Array
            (
                [id] => 10
                [course_id] => 1
                [name] => first course comp 2
            )

        )
    )

)

但是在competencies数组中,我希望找到另一个名为competency_standards的数组,如下所示:

...
[0] => Array
    (
        [id] => 9
        [course_id] => 1
        [name] => first course comp 1
        [competency_standards] => Array
            (
                [0] => Array
                (
                    [id] => 22
                    [competency_id] => 9
                    [name] => standard foo
                )
                [1] => Array
                (
                    [id] => 23
                    [competency_id] => 9
                    [name] => standard bar
                )
            )
    )

...

这可能吗?我会以错误的方式处理吗?

最佳答案

应该可以使用:

 $coursesAndComps = Course::with('competencies', 'competencies.standards')
                   ->get()->toArray();

但是,当然,您需要在standards模型中定义Competency关系,以将CompetencyStandard链接起来

关于Laravel:嵌套 "with()"函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26722342/

10-08 22:15