Sqlalchemy:具有多对多关系的3个表的关联对象

时间:2017-07-13 13:27:57

标签: python sqlalchemy many-to-many associations

我正在研究一个项目,我有3个实体需要与多对多关系一起映射。 假设我的表格是A,B和C.我希望能够知道哪些B和C与A相关联,而B(与As和Cs相关联)和C相同。

我尝试使用Sqlalchemy实现这一点,我的代码如下所示:

class A(Base):
    __tablename__ = 'a'
    a_id = Column(Integer, primary_key=True)

    b_children = relationship("Association")
    c_children = relationship("Association")

class B(Base):
    __tablename__ = 'b'
    b_id = Column(Integer, primary_key=True)

    a_children = relationship("Association")
    c_children = relationship("Association")

class C(Base):
    __tablename__ = 'c'
    c_id = Column(Integer, primary_key=True)

    b_children = relationship("Association")
    c_children = relationship("Association")

class Association(Base):
    __tablename__ = 'associations'
    a_id = Column(Integer, ForeignKey('a.a_id'))
    b_id = Column(Integer, ForeignKey('b.b_id'))
    c_id = Column(Integer, ForeignKey('c.c_id'))

我知道这不应该是这么简单,所以如果这是正确的话,我就是在想...因为我希望能够做a = A()b = B()以及{{1 }}

0 个答案:

没有答案