我有一个包含以下表和关系的数据库:
1-1
车型m-1
品牌m-1
如果我想检索广告,我可以简单地使用:
Advert::find(1);
如果我想要汽车的细节,我可以使用:
Advert::find(1)->with('Car');
但是,如果我还想要模型的细节(遵循与 Car 的关系),语法是什么,以下内容不起作用:
Advert::find(1)->with('Car')->with('Model');
非常感谢
它在"急切加载"下的官方文档中
多种关系:
$books = Book::with('author', 'publisher')->get();
嵌套关系:
$books = Book::with('author.contacts')->get();
所以对你来说:
Advert::with('Car.Model')->find(1);
首先,你需要创建你的关系,
<?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
或者,您必须在关系中指定它们。
假设您有 3 个模型地区、城市、酒店,然后获得所有带有城市和地区的酒店
定义其中的关系如下:-
酒店.php
class Hotel extends Model {
public function cities(){
return $this->hasMany(City::class);
}
public function city(){
return $this->belongsTo('App'City','city_id');
}
}
城市.php
class City extends Model {
public function hotels(){
return $this->hasMany(Hotel::class);
}
public function regions(){
return $this->belongsTo('App'Region','region_id');
}
}
地区.php
class Region extends Model
{
public function cities(){
return $this->hasMany('App'City');
}
public function country(){
return $this->belongsTo('App'Country','country_id');
}
}
酒店控制器.php
public function getAllHotels(){
// get all hotes with city and region
$hotels = Hotel::with('city.regions')->get()->toArray();
}
添加关系函数只是要求所需的关系
public function Car()
{
return $this->belongsTo(Car::class, 'car_id')->with('Model');
}
但是如果你想要一个嵌套的关系,只需使用与
Advert::with('Car.Model')->find(1);
但对于多关系使用数组
Advert::with('Car','Model')->find(1);