2014-11-03 74 views
0

我想從三個表中檢索數據:課程,能力和competency_standards。以下查詢幾乎可以工作,但不會返回關聯的competency_standards表數據。Laravel:嵌套「with()」函數

$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 = competency.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 
       ) 
      ) 
    ) 

...

這可能嗎?我是否以這種錯誤的方式去做?

回答

3

應該可以使用:

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

當然你需要定義standards關係Competency模型Standard

+1

鏈接Competency你甚至都不需要指定'competencies'首先,只有'('competencies.standards')'就足夠了。 – 2014-11-03 20:36:31

+0

@JarekTkaczyk很高興知道 – 2014-11-03 20:50:57