0

i have another issue. I have a Country model:

protected $fillable = [
    'code', 'latitude', 'longitude', 'currency_id', 'timezone', 'dam_date', 'status',
];

public function neighbors() {

    return $this->belongsToMany('App\Models\Country', 'country_country_relation', 'country_id_1', 'country_id_2');

}

I want to show the neighbors of some country. Unfortunately neighbors() works only in one direction.

Example: If i add Austria as neighbor country of Germany, when i look the Germany page i see Austria, but when i see the Austria page i don't find Germany as neighbor. What should i change to make this thing possible ?

Vince Carter
  • 907
  • 3
  • 14
  • 41

1 Answers1

0

What you're asking is Table self reference for many to many relation. In your case the issue is that you are saving in the pivot table an from id to an other. So it can only retrieve in this way. With only one relation you have a problem of key order to be able to fetch them in both ways.

Have a look at this (you ends up with 2 methods to trigger the relation both way) : Laravel Many to many self referencing table only works one way

Better solution here : https://github.com/laravel/framework/issues/441

Community
  • 1
  • 1
Mushr00m
  • 2,258
  • 1
  • 21
  • 30
  • do u mean i should use two functions with changing the fields order ? – Vince Carter Mar 08 '16 at 01:42
  • The two methods is one option. I prefer the one on the last answer (from marco-solaire) on the github issue link in my answer. The idea is to use one relation method but when you add a country neightbor your need the same the other way. So if you add Germany as a France neighbor, you need to add France as a Germany Neighbor. What he did is creating a method to do that both way to add and remove a relation. Read it it's very simple you'll see ;-) – Mushr00m Mar 08 '16 at 01:52
  • aa ok. Thanks for the answer i will think about which option is better for me. – Vince Carter Mar 08 '16 at 01:56