使用Laravel中的Eloquent检索关系关系

Ben*_*son 20 php object-relationships laravel eloquent

我有一个包含以下表和关系的数据库:

广告1-1汽车m-1模型m-1品牌

如果我想要检索广告,我可以简单地使用:

Advert::find(1);
Run Code Online (Sandbox Code Playgroud)

如果我想要汽车的细节,我可以使用:

Advert::find(1)->with('Car');
Run Code Online (Sandbox Code Playgroud)

但是,如果我还想要模型的细节(跟随与Car的关系),语法是什么,以下不起作用:

Advert::find(1)->with('Car')->with('Model');
Run Code Online (Sandbox Code Playgroud)

非常感谢

Bjö*_*örn 65

它位于"Eager Loading"下的官方文档中

多种关系:

$books = Book::with('author', 'publisher')->get();
Run Code Online (Sandbox Code Playgroud)

嵌套关系:

$books = Book::with('author.contacts')->get();
Run Code Online (Sandbox Code Playgroud)

所以对你来说:

Advert::find(1)->with('Car.Model')->get();
Run Code Online (Sandbox Code Playgroud)

  • 文档链接现在是:https://laravel.com/docs/5.5/eloquent-relationships#eager-loading在"嵌套的Eager Loading"下 (3认同)

Ant*_*iro 5

首先你需要建立你的关系,

<?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');
    }

}
Run Code Online (Sandbox Code Playgroud)

然后你只需要通过这种方式访问​​:

echo Advert::find(1)->car->model->brand->name;
Run Code Online (Sandbox Code Playgroud)

但是你的表字段应该是,因为 Laravel 是这样猜测的:

id (for all tables)
car_id
model_id
brand_id
Run Code Online (Sandbox Code Playgroud)

或者您必须在关系中指定它们。