gpt4 book ai didi

python - SQLAlchemy - 如何查询 3 个表(带关联表)

转载 作者:行者123 更新时间:2023-11-28 17:30:32 25 4
gpt4 key购买 nike

我有 3 个表(SQLAlchemy 类):Team、Game 和 GameObserver。每场比赛有 2 个比赛队(进攻和防守),但有许多观察队。

什么查询会返回进攻组电子邮件为 foo@email123.com 的所有比赛观察员(球队)?

class Team(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(120), index=True, unique=True)

class Game(db.Model):
id = db.Column(db.Integer, primary_key=True)
offense_id = db.Column(db.Integer(), db.ForeignKey('team.id'))
defense_id = db.Column(db.Integer(), db.ForeignKey('team.id'))
offense = db.relationship('Team',
foreign_keys=[offense_id], backref='offensive_games')
defense = db.relationship('Team',
foreign_keys=[defense_id], backref='defensive_games')

class GameObserver(db.Model):
id = db.Column(db.Integer, primary_key=True)
observer_id = db.Column(db.Integer(), db.ForeignKey('team.id'))
game_id = db.Column(db.Integer(), db.ForeignKey('game.id'))
game = db.relationship('Game',
foreign_keys=[game_id], backref='game_watchers')
observer = db.relationship('Team',
foreign_keys=[observer_id], backref='watched_games')

我发现一个可行的解决方案是:

db.session.query(Game.id, Team.email).filter(GameObserver.observer_id == 
Team.id).filter(GameObserver.game_id == Game.id).filter(Game.offense.has(email =
'foo@email123.com')).all()

但是,我怀疑有更好的方法可以使用联接来执行此操作。有没有人有更好的方法?

最佳答案

这应该为符合您条件的每个 GameObserver 记录返回一行。

from sqlalchemy.orm import aliased

off_Team = aliased(Team)
obs_Team = aliased(Team)

results = db.session.query(obs_Team.email, Game.id)\
.select_from(GameObserver)\
.join(Game)\
.join(obs_Team, GameObserver.observer)\
.join(off_Team, Game.offense)\
.filter(off_Team.email == 'foo@email123.com')\
.all()

关于python - SQLAlchemy - 如何查询 3 个表(带关联表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34688555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com