簡體   English   中英

鄰接表關系在 SQLAlchemy 中是如何工作的?

[英]How does the Adjacency List Relationships works in SQLAlchemy?

我正在閱讀SQLAlchemy文檔,但對給定的示例感到困惑:

class Node(Base):
    __tablename__ = 'node'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('node.id'))
    data = Column(String(50))
    children = relationship("Node")

我知道一個 Node 對象可以通過這個類定義有很多孩子。 我的理解是在創建和保存一個Node對象時,會在數據庫中插入一條記錄(id, parent_id, data),我知道默認會生成id ,但是parent_id是怎么生成的呢? 我在我的項目中嘗試了類似的用法,但parent_id保持None

parent_id並不是真正生成的,它是使用對象之間的實際關系分配的。 這就是說sqlalchemy會將parent_id正確保存到關系Node.children所有子Node.children

例如,為了實現sqlalchemy的文檔中記錄的關系圖,您鏈接到:

root --+---> child1
       +---> child2 --+--> subchild1
       |              +--> subchild2
       +---> child3

您可以通過以下方式編寫代碼:

root = Node(
    data='root',
    # @NOTE: all Node under this children will have `parent_id` point to the `id` of this (root) Node
    children=[
        Node(data='child1'),
        Node(data='child2',
             children=[
                 Node(data='subchild1'),
                 Node(data='subchild2'),
             ]),
        Node(data='child3')
    ]
)

session.add(root)  # this will also add all the other nodes in the graph
session.commit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM