简体   繁体   English

邻接表关系在 SQLAlchemy 中是如何工作的?

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

I am reading the SQLAlchemy docs and get confused by the given example:我正在阅读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")

I know a Node object can have many children by this class definition.我知道一个 Node 对象可以通过这个类定义有很多孩子。 My understanding is when creating and saving a Node object, a record (id, parent_id, data) will be inserted into the database, I know id will be generated by default, but how is the parent_id generated?我的理解是在创建和保存一个Node对象时,会在数据库中插入一条记录(id, parent_id, data),我知道默认会生成id ,但是parent_id是怎么生成的呢? I tried a similiar usage in my project, but the parent_id stays None .我在我的项目中尝试了类似的用法,但parent_id保持None

parent_id is not really generated, it is assigned using the actual relationships between objects. parent_id并不是真正生成的,它是使用对象之间的实际关系分配的。 This is to say that sqlalchemy will save proper the parent_id to all the children the relationship Node.children .这就是说sqlalchemy会将parent_id正确保存到关系Node.children所有子Node.children

For example, in order to achieve the relationship graph as documented in the sqlalchemy 's documentation you link to:例如,为了实现sqlalchemy的文档中记录的关系图,您链接到:

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

you may write a code in the following way:您可以通过以下方式编写代码:

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