2017-08-22 130 views
0

我尝试acomplish有3种型号的关系:流明/ laravel雄辩hasManyThrough 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'); 
} 

结果是768,16:

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(); 

我知道我的模型不正确命名。城市(单数),邻居(单数),区块(单数)但传递参数应该工作。 我只是不知道为什么它不起作用。基于@Gaurav清莱的响应

首先,

RELATIONSSHIP解决方案,我的模型是错误的命名。请condider命名例如使用复数数据库:奇异例如城市,街区,街区和你的模型:基于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

我认为你们的关系没有得到很好的定义:

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

块.PH p

public function neighbourhoods() 
{ 
    return $this->belongsTo('App\Neighbourhoods'); 
} 
+0

谢谢先生。我更新了我的答案。 –