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

时间:2013-09-23 15:44:44

标签: php laravel eloquent object-relationships

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

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

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

Advert::find(1);

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

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

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

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

非常感谢

3 个答案:

答案 0 :(得分:48)

这是在“Eager Loading”下的官方documentation

多重关系:

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

嵌套关系:

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

所以对你:

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

答案 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

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

答案 2 :(得分:0)

假设您具有3个区域,城市,酒店的模型,然后获得所有具有城市和区域的酒店

在其中定义关系如下:-

Hotel.php

class Hotel extends Model {

  public function cities(){
        return $this->hasMany(City::class);
  }

  public function city(){
        return $this->belongsTo('App\City','city_id');
  }
}

City.php

class City extends Model {

  public function hotels(){
      return $this->hasMany(Hotel::class);
  }

  public function regions(){
      return $this->belongsTo('App\Region','region_id');    
  }
}

Region.php

class Region extends Model
{

  public function cities(){
      return $this->hasMany('App\City');    
  }

  public function country(){
      return $this->belongsTo('App\Country','country_id');
  } 
}

HotelController.php

public function getAllHotels(){
    // get all hotes with city and region
    $hotels = Hotel::with('city.regions')->get()->toArray();

}
相关问题