yii2has-manyyii2-modelyii-relations

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?


Solution

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

    and while calling

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