简体   繁体   中英

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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM