16

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?

1 Answer 1

36

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

Sign up to request clarification or add additional context in comments.

1 Comment

You don't even need to specify competencies first, just with('competencies.standards') is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.