我有以下型号:
class A(Base):
__tablename__ = 'A'
a_id = Column(Integer, primary_key=True)
class B(Base):
__tablename__ = 'B'
b_id = Column(Integer, primary_key=True)
class C(Base):
__tablename__ = 'C'
c_id = Column(Integer, primary_key=True)
class AB(Base):
__tablename__ = 'A_B'
a_id = Column(Integer, ForeignKey(A.a_id), primary_key=True)
b_id = Column(Integer, ForeignKey(B.b_id), primary_key=True)
class BC(Base):
__tablename__ = 'B_C'
b_id = Column(Integer, ForeignKey(B.b_id), primary_key=True)
c_id = Column(Integer, ForeignKey(C.c_id), primary_key=True)
我想要的是使用多对多表b_id作为连接列添加A和C之间的关系。我知道当通过一个多对多表存在关系时,我可以使用seconday和secondaryjoin来完成它,但我不知道如何使用2个多对多表来执行此操作。
我想要这样的事情:
class A(Base):
a_id = Column(Integer, primary_key=True)
c_colletion = relationship(?)
答案 0 :(得分:2)
您可以使用自定义辅助:
ab = AB.__table__
bc = BC.__table__
ac = select([ab.c.a_id, bc.c.c_id]).select_from(ab.join(bc, ab.c.b_id == bc.c.b_id))
A.c_collection = relationship("C", secondary=ac,
primaryjoin=A.a_id == ac.c.a_id,
secondaryjoin=ac.c.c_id == C.c_id)