I am new to Laravel and I struck an interesting logic twist I want to implement as Eloquent relationships in each class, so would appreciate some advice as I am not getting the expected output (rather than cheating and using query builder!). I thought this previous question was very useful but I cannot get it working all the same.
Two tables: regions
and neighbour_regions
Table: `regions`
id region
1 argentina
2 brazil
....
Table: `neighbour_regions`
id region_id neighbour_region_id
1 1 2
2 1 3
....
I have a class for each table and set up recursive relationships as follows:
Class: Region
/**
* A Region as a Neighbour to another Region
*/
public function region()
{
return $this->hasMany(NeighbourRegion::class, 'region_neighbour_id', 'id');
}
Class NeighbourRegion
/**
* A Region has many Neighbours
*/
public function childrenNeighbourRegions()
{
return $this->hasMany(NeighbourRegion::class, 'region_id', 'neighbour_region_id');
}
/**
* A Region has many Neighbours
*/
public function allChildrenNeighbours()
{
return $this->childrenNeighbourRegions()->with('allChildrenNeighbours');
}
I then call the request to list all neighbours to a region in my controller like so:
$region = Region::where('region', '=', $region_name)->get();
return NeighbourRegion::with('allChildrenNeighbours')->where('region_id', '=', $region[0]->region_id)->get();
But I end up with an empty collection when I pass the value argentina
to it (for example). I can clearly see the value getting to the first call and the id I resolve from it for the second call is correct. What I would like access to is the region (by name) and each neighbouring region (by name also).
What am I missing with the relationship set up? Many thanks!!
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire