Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: nested "with()" function

I want to retrieve data from three tables: courses, competencies and competency_standards. The following query almost works, but it does not bring back the associated competency_standards table data.

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

Where the competencies table is linked to the courses table (competencies.course_id = course.id) and the competency_standards table links to the competencies table (competency_standards.competencey_id = competency.id).

The array returned looks like this:

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
            )

        )
    )

)

but within the competencies array, I was hoping to find another array called competency_standards like this:

...

[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 
                )
            )
    )

...

Is this possible? Am I going about this the wrong way?

like image 724
superUntitled Avatar asked Nov 03 '14 20:11

superUntitled


1 Answers

It should be possible to use:

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

but of course you need to have defined standards relationship in Competency model to link Competency with Standard

like image 136
Marcin Nabiałek Avatar answered Nov 10 '22 10:11

Marcin Nabiałek