我尝试与3个模型建立关系:
Cities.php //table cities
id
name
Neighbourhoods.php //table neighbourhoods
id
name
city_id
Blocks.php //table blocks
id
name
neighbourhood_id
我的模特看起来像这样: Cities.php
public function neighbourhoods()
{
return $this->hasManyThrough('App\Neighbourhoods', 'App\Blocks', 'neighbourhood_id', 'city_id', 'id');
}
Neighbourhoods.php
public function blocks()
{
return $this->hasMany('App\Blocks', 'neighbourhood_id', 'id');
}
Blocks.php
public function neighbourhoods()
{
return $this->belongsToMany('App\Neighbourhoods', 'neighbourhood_id', 'id');
}
结果应该是:
results
city1:
neighbourhoods:
neighbourhood1:
block1
block2
block3
neighbourhood2
block1
block2
city2:
neighbourhoods:
neighbourhood1:
blocks:
block1
block2
block3
neighbourhood2:
blocks:
block1
block2
调用结果:
return Blocks::with('neighbourhoods')->get();
我知道我的模型没有正确命名。城市(奇异),邻居(singlar),Block(奇异)但传递参数shoud工作。 我无法弄清楚它为什么不起作用。
基于@Gaurav Rai回应的关系解决方案
首先,我的模型命名错误。请使用复数形式命名数据库,例如:城市,邻域,块和模型,例如:City.php,Neighbourhood.php和Block.php
根据我的问题,解决方案是:
Cities.php
public function neighbourhoods()
{
return $this->hasMany('App\Neighbourhoods', 'city_id', 'id');
// because my model is called Cities.php,
// the function will look by default
// for the column cities_id in neighbourhoods table,
// thats why we need to specifiy city_id column
}
public function blocks()
{
return $this->hasManyThrough('App\Blocks', 'App\Neighbourhoods', 'city_id', 'neighbourhood_id', 'id');
}
Neighbourhoods.php
public function cities()
{
return $this->belongsTo('App\Cities', 'city_id', 'id');
}
public function blocks()
{
return $this->hasMany('App\Blocks', 'neighbourhood_id','id');
}
Blocks.php
public function neighbourhoods()
{
return $this->belongsTo('App\Neighbourhoods', 'neighbourhood_id');
}
调用关系:
return Cities::with(['neighbourhoods', 'blocks'])->get();
答案 0 :(得分:0)
我认为您的关系定义不明确:
Cities.php
public function neighbourhoods()
{
return $this->hasMany('App\Neighbourhoods');
}
public function blocks()
{
return $this->hasManyThrough('App\Neighbourhoods', 'App\Blocks');
}
Neighbourhoods.php
public function blocks()
{
return $this->hasMany('App\Blocks');//by default it will consider id
}
public function city()
{
return $this->belongsTo('App\City');
}
Blocks.php
public function neighbourhoods()
{
return $this->belongsTo('App\Neighbourhoods');
}