[英]Many-to-many relationship on same table with association object
Related (for the no-association-object use case): SQLAlchemy Many-to-Many Relationship on a Single Table 相关(对于无关联对象用例): SQLAlchemy单表上的多对多关系
Building a many-to-many relationship is easy. 建立多对多关系很容易。 Building a many-to-many relationship on the same table is almost as easy, as documented in the above question. 如上面的问题所述,在同一个表上建立多对多关系几乎一样容易。
Building a many-to-many relationship with an association object is also easy. 与关联对象建立多对多关系也很容易。
What I can't seem to find is the right way to combine association objects and many-to-many relationships with the left and right sides being the same table. 我似乎无法找到的是将关联对象和多对多关系组合在一起的正确方法,左右两侧是同一个表。
So, starting from the simple, naïve, and clearly wrong version that I've spent forever trying to massage into the right version: 所以,从简单,天真,明显错误的版本开始,我花了很长时间试图按摩到正确的版本:
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),
})
What's the right way to map this relationship? 映射这种关系的正确方法是什么?
I guess you are getting an error like Could not determine join condition between parent/child tables...
In this case, Change the mapper for Group_To_Group
to the following: 我猜你得到的错误就像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),),
})
also you might want to add the backref
so that you can navigate the relations from the Group
objects as well. 您也可以添加backref
以便也可以从Group
对象中导航关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.