lumen/laravel Eloquent hasManyThrough 3 models relation -
i try acomplish relation 3 models:
cities.php //table cities id name neighbourhoods.php //table neighbourhoods id name city_id blocks.php //table blocks id name neighbourhood_id
my models looks this: 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'); }
the result shoud be:
results city1: neighbourhoods: neighbourhood1: block1 block2 block3 neighbourhood2 block1 block2 city2: neighbourhoods: neighbourhood1: blocks: block1 block2 block3 neighbourhood2: blocks: block1 block2
calling results:
return blocks::with('neighbourhoods')->get();
i know models not named. city (singular), neighbourhood (singlar), block (singular) passing parameters shoud work. can't figure our why not work.
relationsship solution based on @gaurav rai's response
first of all, models wrong named. please condider naming database using plurals example: cities, neighbourhoods, blocks , models singular example: city.php, neighbourhood.php , block.php
based on problem, solution is:
cities.php
public function neighbourhoods() { return $this->hasmany('app\neighbourhoods', 'city_id', 'id'); // because model called cities.php, // function default // column cities_id in neighbourhoods table, // thats why need 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'); }
calling relation:
return cities::with(['neighbourhoods', 'blocks'])->get();
i think relationships not defined:
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 consider id } public function city() { return $this->belongsto('app\city'); }
blocks.php
public function neighbourhoods() { return $this->belongsto('app\neighbourhoods'); }
wiki
Comments
Post a Comment