Mathias
Mathias

Reputation: 334

Yii2: How to declare a has-many relation where either of two attributes match an id?

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?

Upvotes: 0

Views: 933

Answers (1)

Kandarp Patel
Kandarp Patel

Reputation: 1020

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

and while calling

$games = $model->getGames($model->id);

Upvotes: 1

Related Questions