0

I have two tables: players and battles. When a player dwells another one, a new row is inserted on the battles table where the id for challenger player is stored on player1_id column and the challenged player is stored on player2_id

My battles table looks like so:

  • id
  • player1_id (challenger player)
  • player2_id (challenged player)
  • ...

What I need is to have a hasMany relationship between players to battles matching either of the columns.


I found a solution for an almost identical issue and tried what user Colling James suggested https://stackoverflow.com/a/29775608/1481559 but it didn't work for me.


Another solution I tried was using union as per Acasar's suggestion on https://laracasts.com/discuss/channels/eloquent/combining-multiple-hasmany-relationships-into-one-model-relation-query-builder

public function battles() {
    return $this->hasMany('App\Battle')->union($this->hasMany('App\Battle')->toBase());
}

but I had no success.

Amorim
  • 15
  • 9

1 Answers1

3

I think in your case it's not important to return a hasMany object because it would be impossible to add. I think there is no solution because a 1 to n relationship needs one field for the foreign key and not an or-statement.

If you just want to return the battles in an array you can do this:

public function battles() {
    return App\Battle::where('player1_id', $this->id)->orWhere('player2_id', $this->id)->get();
}

In this case you just have one query. Otherwise you can fire up 2 has many queries where you link first to the one id, than to the other one and then merge them, but I think the solution above is the easiest one.

If you want to work with has many you can try this (maybe it does not work because the foreign key is not set in the db)

public function battlesChallenger() {
    return $this->hasMany('App\Battle', 'player1_id');
}

public function battlesChallenged() {
    return $this->hasMany('App\Battle', 'player2_id');
}

public function battles() {
    return $this->battlesChallenger()->merge($this->battlesChallengered());
}
cre8
  • 13,012
  • 8
  • 37
  • 61
  • your second suggestion didn't work, it gave me "Call to undefined relationship [battles] on model [App\Player]". Either way, I decided to go the first way. Many thanks! – Amorim Jul 03 '17 at 22:07
  • I think because the merge call won't give you a relationship but an array back. You are welcome – cre8 Jul 04 '17 at 04:47