Retrieving relationships of relationships using Eloquent in Laravel

允我心安 提交于 2019-11-29 06:01:02

问题


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


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/18963483/retrieving-relationships-of-relationships-using-eloquent-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!