[英]SQLAlchemy. 2 different relationships for 1 column
I have a simple many-to-many relationship with associated table: 我与关联表有一个简单的多对多关系:
with following data: 具有以下数据:
matches: 火柴: users: 用户:
users_mathces: users_mathces:
ONE user can play MANY matches and 一个用户可以玩很多场比赛,
ONE match can involve up to TWO users 一场比赛最多可涉及两个用户
I want to realize proper relationships in both "Match" and "User" classes 我想在“匹配”和“用户”类中实现适当的关系
users_matches_table = Table('users_matches', Base.metadata,
Column('match_id', Integer, ForeignKey('matches.id', onupdate="CASCADE", ondelete="CASCADE")),
Column('user_id', Integer, ForeignKey('users.id', onupdate="CASCADE", ondelete="CASCADE"))
)
class Match(Base):
__tablename__ = 'matches'
id = Column(Integer, primary_key=True)
#relations
user1 = relationship('User', secondary = users_matches_table)
user2 = relationship('User', secondary = users_matches_table)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String)
#relations
matches = relationship('Match', secondary=users_matches_table)
But obviously, there should be some rules for Match.user1 and Match.user2 relationships, that will differ one User from another, so i could get match1.user1
and match1.user2
and they won't reference to the same User. 但显然,对于Match.user1和Match.user2关系应该有一些规则,一个用户与另一个用户之间的差异,因此我可以得到match1.user1
和match1.user2
并且它们不会引用同一用户。 Any ideas how to do that? 任何想法如何做到这一点?
I'm afraid you can't do it like this. 恐怕你不能这样做。 I suggest you have just one relationship users
and validate the insert queries. 我建议您只有一个关系users
并验证插入查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.