mardi 6 octobre 2015

Laravel 5.1 recursive relationship in Eloquent

I have two tables that link to each other, one recursive.

regions
id   region
1    argentina
2    brazil
3    chile
...

neighbour_regions
id   region_id    neighbour_region_id
1    1            2
2    1            3
....

I have two classes:

Region:

public function withNeighbours()
{
    return $this->hasMany(NeighbourRegion::class, 'region_id', 'id')->hasOne(Region::class, 'neighbour_region_id', 'id');
}

public function asNeighbourOf()
{
    return $this->hasOne(NeighbourRegion::class, 'neighbour_region_id', 'id')->hasOne(Region::class, 'neighbour_region_id', 'id');
}

NeighbourRegion:

public function neighbours()
{
    return $this->hasMany(NeighbourRegion::class, 'region_id', 'neighbour_region_id');
}

public function neighbourNames()
{
    return $this->neighbours->hasOne(Region::class, 'id', 'neighbour_region_id');
}

I am trying to return all neighbours to a region (supplied by name, not id). The end result I am trying to achieve is something like:

$region->withNeighbours()->get();

For the $region being an instance of its class with value argentina, this should return something like:

region      neighbour_region
argentina   brazil
argentina   chile
....

My controller contains this method

public function fetchNeighbours(Request $request, $region_name)
{
    $region = Region::where('region', '=', $region_name)->get();

    return $region->withNeighbours()->get();
}

Which returns this error:

Call to undefined method Illuminate\Database\Eloquent\Collection::withNeighbours()

And this after numerous iterations from looking at examples. I am just not getting it. Any help is greatly appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire