0

The model Team has two has-many relations to Game:

public function getGamesWhereTeamIsSetAsHome()
{
    return $this->hasMany(Game::className(), ['teamHome' => 'id']);
}

public function getGamesWhereTeamIsSetAsAway()
{
    return $this->hasMany(Game::className(), ['teamAway' => 'id']);
}

I would like a has-many relation that returns all games, which have either teamHome or teamAway set to the id of team (like a combo of the two relations above).

public function getGames()
{
    return /* code here */;
 }

How do I set up such a relation?

Mathias
  • 334
  • 3
  • 5
  • 22
  • 1
    First of all understand how the hasMany relation method work in yii2, the second parameter is an array of primary key - foreign key constraint (attributes of corresponding classes) so there is no way you can add an OR condition in that function.Nor you can keep it empty, so you have to change your approach for achieving this – Kandarp Patel May 17 '16 at 20:19
  • 1
    What's 'teamUp', 'teamDown' meaning? Can you mark this as 'type' or 'category' at Team table? – Xiaosong Guo May 18 '16 at 06:42
  • @KandarpPatel You're right, I've edited my question accordingly. – Mathias May 18 '16 at 08:41
  • @XiaosongGuo: I just renamed them for more clarity. They're like the two oppenents in a game. – Mathias May 18 '16 at 08:46
  • @Mathias This is kind of homework but did it :) next time think for simple solutions first. – Kandarp Patel May 18 '16 at 10:52
  • @Mathias I would like change 'teamHome', teamAway' to 'team_id', and add a new column 'is_home_team(boolean)' at Geam table. Then you can easily get games with relationship, get 'gamesAsHomeTeam' with 'where' condition and get 'gamesAsHomeAway' with 'where' condition also. – Xiaosong Guo May 19 '16 at 02:49

1 Answers1

1
public function getGames($id)
{
   return Games::find()->where(['or',['teamHome'=>$id],['teamAway'=>$id]])->all();
}

and while calling

$games = $model->getGames($model->id);
Kandarp Patel
  • 1,045
  • 9
  • 21