Ciaran
Ciaran

Reputation: 215

sqlalchemy - several joins from one table to another

I have two tables. The first is the Match table, which represents a football game with two teams. The second is a Team table which represents a team. There will be approximately 18 teams in the Team table. There will be approximately 34 matches in the Match table.

Rather than creating a many-to-many join what I'd like to do is create a simple join for:

Match.matchID --------------------> 1

Match.team1 ----------------------> Team.teamID

Match.team2 ----------------------> Team.teamID

There can be only a single teamID for Match.team1 and a single teamID for Match.team2. How would I go about doing this in classicaly sqlalchemy? I currently have the following for the Match table:

match_table = Table('match',metadata,
  Column('matchID', Integer, primary_key=True),
  Column('matchTeam1',Integer,ForeignKey('team.teamID')),
  Column('matchTeam2',Integer,ForeignKey('team.teamID')),

and the following for the Team table:

team_table = Table('team',metadata,
  Column('teamID',Integer,primary_key=True),
  Column('teamShortName',String),

How would I go about creating a mapping here? Something like the following does not seem to work - is there a different syntax to use?

mapper(Match,match_table,properties={
  'team1':relationship(Team),
  'team2':relationship(Team),
})

Upvotes: 0

Views: 102

Answers (1)

Vladimir Iliev
Vladimir Iliev

Reputation: 241

    mapper(Match,match_table,properties={
      'team1':relationship(Team, foreign_keys=[match_table.c.matchTeam1], 
          primaryjoin=match_table.c.matchTeam1==team_table.teamID),
      'team2':relationship(Team, foreign_keys=[match_table.c.matchTeam2], 
          primaryjoin=match_table.c.matchTeam2==team_table.teamID),
    })

Upvotes: 1

Related Questions