Home » Php » Retrieving relationships of relationships using Eloquent in Laravel

Retrieving relationships of relationships using Eloquent in Laravel

Posted by: admin November 30, 2017 Leave a comment

Questions:

I have a database with the following tables and relationships:

Advert 1-1 Car m-1 Model m-1 Brand

If I want to retrieve an Advert, I can simply use:

Advert::find(1);

If I want the details of the car, I could use:

Advert::find(1)->with('Car');

However, if I also want the detail of the Model (following the relationship with Car), what would the syntax be, the following doesn’t work:

Advert::find(1)->with('Car')->with('Model');

Many thanks

Answers:

It’s in the official documentation under “Eager Loading”

Multiple relationships:

 $books = Book::with('author', 'publisher')->get();

Nested relationships:

$books = Book::with('author.contacts')->get();

So for you:

Advert::find(1)->with('Car.Model')->get();

Questions:
Answers:

First you need to create your relations,

<?php

class Advert extends Eloquent {

    public function car()
    {
        return $this->belongsTo('Car');
    }

}

class Car extends Eloquent {

    public function model()
    {
        return $this->belongsTo('Model');
    }

}

class Model extends Eloquent {

    public function brand()
    {
        return $this->belongsTo('Brand');
    }

    public function cars()
    {
        return $this->hasMany('Car');
    }

}

class Brand extends Eloquent {

    public function models()
    {
        return $this->hasMany('Model');
    }

}

Then you just have to access this way:

echo Advert::find(1)->car->model->brand->name;

But your table fields shoud be, because Laravel guess them that way:

id (for all tables)
car_id
model_id
brand_id

Or you’ll have to specify them in the relationship.