【问题标题】:SQLALCHEMY - many many-to-many unary relationshipsSQLALCHEMY - 多对多一元关系
【发布时间】:2018-06-03 04:54:40
【问题描述】:

我有一个名为 Node.js 的表。每个节点都有许多节点类型的子节点。此外,一个 Node 对象有许多父对象。我还做了一个算法来寻找兄弟姐妹(具有相似父母的节点)

如何制作?我要为他们单独制作一张桌子吗?还是我把它放在同一张桌子上?以下是我尝试这样做但显然失败的方法:

class Node(Model):
    id = Column(String, primary_key=True)
    name = Column(String)
    parent_id = db.Column(db.String, db.ForeignKey('node.id'))

    children = db.relationship('node', remote_side=[id], uselist=True)
    parents = db.relationship('node', remote_side=[id], uselist=True)
    siblings = db.relationship('node', remote_side=[id], uselist=True)

我不知道如何做到这一点。

我实际上考虑过为这个节点对象使用 graphDB。以及其他具有经典 SQL 的表,但我不确定是否值得大惊小怪

【问题讨论】:

  • 您是否尝试实现Adjacency list relationships
  • @daveruinseverything 不完全。根据文档邻接列表是“树状”。我想要一个“类似图形”的结构。并根据您提供的暗示。每个节点都有一个父节点,我喜欢每个节点都有很多父节点

标签: python postgresql flask sqlalchemy flask-sqlalchemy


【解决方案1】:

虽然我还不知道如何实现“兄弟姐妹”,但这里是如何拥有许多自引用的多对多关系:

Connection = Table('connection',
    Column('child_id', String, ForeignKey('node.id')),
    Column('parent_id', String, ForeignKey('node.id')),
    UniqueConstraint('parent_id', 'child_id', name='unique_usage')
)


class Node(Model):
    id = Column(String, primary_key=True)
    name = Column(String)

    # this is the result list of type Node 
    # where the current node is the "other party" or "child"
    parents = relationship('Node', secondary=Connection, 
                            primaryjoin=id == Connection.c.parent_id,
                            secondaryjoin=id == Connection.c.child_id)

    # this is the result list of type Node 
    # where the current node is the "parent" 
    children = relationship('Node', secondary=Connection, 
                            primaryjoin=id == Connection.c.child_id,
                            secondaryjoin=id == Connection.c.parent_id)

基本上,对于每个想要的多对多关系,制作代表关系的表格,然后将关系添加到您的模块中。您可以为它们中的每一个建立双向关系

稍后我会在弄清楚如何制作兄弟姐妹时编辑我的答案

【讨论】:

    猜你喜欢
    • 2012-06-14
    • 1970-01-01
    • 2016-06-15
    • 2021-08-31
    • 2023-03-04
    • 1970-01-01
    • 2019-12-06
    • 2014-05-26
    • 1970-01-01
    相关资源
    最近更新 更多