Using union in relation and eager loading it cause error.

There seems to be a problem with eager loading a relation when a union has been used.




class Team extends ActiveRecord

{

    ...

    public function getTeam1Games()

    {

        return $this->hasMany(Game::className(), ['team1Id' => id]);

    }


    public function getTeam2Games()

    {

        return $this->hasMany(Game::className(), ['team2Id' => id]);

    }


    public function getGamesPlayed()

    {

        return $this->getTeam1Games()->union($this->getTeam2Games());

    }

}



When gamesPlayed is eager loaded, only the $this->getTeam1Games() retults are returned, but when it is lazy loaded, both results are returned.




$team = Team::find()->where(['id'] => 1)->one();

var_dump($team->gamesPlayed); // both team1 and team2 games are returned;


$team = Team::find()->where(['id'] => 1)->with(['gamesPlayed'])->one();

var_dump($team->gamesPlayed); // only team1 games are returned.



FYI: the sql generated are:




(SELECT * FROM `game` WHERE `team1Id`=1) UNION ( SELECT * FROM `game` WHERE 0=1)



The union part in the sql is not correct. When eager loading was removed, the sql generated was:




(SELECT * FROM `game` WHERE `team1Id`=1) UNION ( SELECT * FROM `game` WHERE `team2Id`=1)



Does anyone have a workaround for this, or any fix?