Home » Php » How to chain DB relationships in Laravel (multiple has_many?)

How to chain DB relationships in Laravel (multiple has_many?)

Posted by: admin October 29, 2017 Leave a comment

Questions:

I’m using Laravel, which is awesome, but I’m stuck on an issue with the database.

Let’s say we have three tables, like so:

TABLE 1: pages

id    |   route   |  title

TABLE 2: elements

id    |   page_id   |  type

TABLE 3: content

id    |   element_id   |  data

I’d like to do a single selection for the page that will in turn select all of the elements with that page id, and for each of the elements it should select all of the content rows with the element id.

I want to have a static load_by_route($route) function in the Page model that, when called, will use the route to load and return the page info as well as the elements and content as described above. Ideally it would return a single object/array with all of this info.

Basically, I’m not sure how to chain the has_many() calls together so that I get the two-level relationship.

Answers:

Look into eager loading. This should do what you want.

class Page extends Eloquent {

    public function elements()
    {
        return $this->has_many( 'Element' );
    }

}

class Element extends Eloquent {

    public function contents()
    {
        return $this->has_many( 'Content' );
    }

}

class Content extends Eloquent {}

$page = Page::with( array( 'elements', 'elements.contents' ) )->first();

https://laravel.com/docs/master/eloquent-relationships#eager-loading