简体   繁体   中英

Lumen 5.4 hasMany relationship on two columns to same model

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.

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM