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

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

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

如果我想检索广告,我可以使用:

Advert::find(1);

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

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

但是,如果我也想要模型的细节(遵循与Car的关系),那么语法是什么,以下内容不起作用:

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

非常感谢


答案 1

它位于“Eager Load”下的官方文档中

多重关系:

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

嵌套关系:

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

所以对你来说:

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

答案 2

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

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

}

然后,您只需要以这种方式访问:

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

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

id (for all tables)
car_id
model_id
brand_id

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


推荐