0

Is it possible to declare 2 relation to the same table in yii2?

Example:

tournament(id, name)
game(id, tournamentId, team1Id, team2Id)
team(id, name)
player(id, name, teamId)

So here is the schema and as you can see, a game should consist of 2 team, team1 and team2.

Now in the Tournament Model in yii, i need to create a relation which would give me the teams who participated in the tournament.

public class Tournament extends ActiveRecord
{
    ...
    public function getGames()
    {
        return $this->hasMany(Game::className(), ['tournamentId' => 'id']);
    }

    public function getParticipatedTeams()
    {
        return $this->hasMany(Team::className(), [/*what should the link be?    */])->via('games');
    }
}

How do i get the teams from the tournament model??

GAMITG
  • 3,810
  • 7
  • 32
  • 51
user2707590
  • 1,066
  • 1
  • 14
  • 28
  • /*what should the link be? kindly mention your condition – Santosh Nov 30 '15 at 11:50
  • Just to link tournament to teams via the ids. that is tournament.id = game.team1Id or tournament.id = game.team2Id – user2707590 Nov 30 '15 at 11:59
  • I can't think in a way of doing this without using a loop (in your games), merging the two `hasmany`s or something similar to this... As far as i read `hasMany` method does not accept `or` =/ – Clyff Nov 30 '15 at 14:34
  • nvm. i figuret it out how to do this. we cannot use `or` in `hasMany`, but we can use the `union`. – user2707590 Dec 01 '15 at 10:08

1 Answers1

0
public class Tournament extends ActiveRecord
{
    ...
    public function getGames()
    {
        return $this->hasMany(Game::className(), ['tournamentId' => 'id']);
    }

    public function getParticipatedTeam1()
    {
        return $this->hasMany(Team::className(), ['id' => 'team1Id'])->via('games');
    }

    public function getParticipatedTeam2()
    {
        return $this->hasMany(Team::className(), ['id' => 'team2Id'])->via('games');
    }
}
Double H
  • 4,120
  • 1
  • 15
  • 26
  • This i already know, what i want to know is that if it is possible to get it in a single function getParticipatedTeams() which would return both for team1 and team2 – user2707590 Nov 30 '15 at 13:02