Last Updated: February 25, 2016
·
10.81K
· buchin

Has many through in Laravel

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.

Create models relationships for the following models:

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 {}

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

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

More Info:
http://laravel.com/docs/database/eloquent#eager
http://stackoverflow.com/questions/15281163/how-to-chain-db-relationships-in-laravel-multiple-has-many

2 Responses
Add your response

How would I change this to just get the third level of information? In this case, just the results from the "content" table, without everything else?

over 1 year ago ·

It turns out that using the HasManyThrough relation will allows this pretty easily.

over 1 year ago ·
  NODES
Community 1
iOS 2
Javascript 5
os 5