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

891 Views Asked by At

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?

1

There are 1 best solutions below

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

and while calling

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