代码之家  ›  专栏  ›  技术社区  ›  Nicholas Knight

具有关联对象的同一表上的多对多关系

  •  4
  • Nicholas Knight  · 技术社区  · 16 年前

    相关(对于无关联对象用例): 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),
    })
    

    怎么回事

    1 回复  |  直到 9 年前
        1
  •  6
  •   van    16 年前

    我猜你会犯这样的错误 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 对象也是。