Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 761
Pete Avatar asked Mar 07 '13 20:03

Pete


People also ask

How many types of relationships are there in Laravel?

One To One (Polymorphic) One To Many (Polymorphic) Many To Many (Polymorphic)

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is hasMany relationship in Laravel?

hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .

What is belongsTo in Laravel?

BelongsTo relationship in laravel is used to create the relation between two tables. belongsTo means create the relation one to one in inverse direction or its opposite of hasOne. For example if a user has a profile and we wanted to get profile with the user details then we can use belongsTo relationship.


1 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

like image 127
Collin James Avatar answered Oct 02 '22 09:10

Collin James