相关(对于无关联对象用例):SQLAlchemy Many-to-Many Relationship on a Single Table
建立多对多关系很容易。如上述问题所述,在同一张表上建立多对多关系几乎一样简单。
使用关联对象建立多对多关系也很容易。
我似乎找不到将关联对象和多对多关系组合在一起的正确方法,左侧和右侧是同一个表。
因此,从简单、幼稚且明显错误的版本开始,我一直试图将其融入正确版本:
t_groups = Table('groups', metadata,
Column('id', Integer, primary_key=True),
)
t_group_groups = Table('group_groups', metadata,
Column('parent_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False),
Column('child_group_id', Integer, ForeignKey('groups.id'), primary_key=True, nullable=False),
Column('expires', DateTime),
)
mapper(Group_To_Group, t_group_groups, properties={
'parent_group':relationship(Group),
'child_group':relationship(Group),
})
映射这种关系的正确方法是什么?
最佳答案
我猜你遇到了类似Could not determine join condition between parent/child tables...
这样的错误
在这种情况下,将 Group_To_Group
的映射器更改为以下内容:
mapper(Group_To_Group, t_group_groups, properties={
'parent_group':relationship(Group,
primaryjoin=(t_group_groups.c.parent_group_id==t_groups.c.id),),
'child_group':relationship(Group,
primaryjoin=(t_group_groups.c.child_group_id==t_groups.c.id),),
})
您可能还想添加 backref
以便您也可以从 Group
对象中导航关系。
关于python - 具有关联对象的同一张表上的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3043770/