gpt4 book ai didi

Laravel:嵌套 "with()"函数

转载 作者:行者123 更新时间:2023-12-02 11:25:50 27 4
gpt4 key购买 nike

我想从三个表中检索数据:类(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com