[英]SQLALCHEMY - many many-to-many unary relationships
I have a table called Node. 我有一个名为Node的表。 Each node has many children of type Node. 每个节点都有许多Node类型的子节点。 Also, a Node object has many parents. 此外,Node对象有许多父对象。 I also made an algorithm to find siblings (node with similar parents) 我还制定了一种算法来查找兄弟姐妹(具有相似父母的节点)
how to make it? 怎么做? do I make a separate table for them? 我要为他们做一张单独的桌子吗? or do I make it in the same table? 还是我在同一张桌子上做? here is how I tried to do it and failed obviously: 这是我尝试执行的操作,但显然失败了:
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)
I have no idea how to make this happen. 我不知道该如何实现。
I actually thought about using a graphDB for this node object. 我实际上考虑过为该节点对象使用graphDB。 And the other tables with classic SQL but I am not sure it is worth the fuss 和其他带有经典SQL的表,但我不确定是否值得大惊小怪
Although I don't know how to implement "siblings" yet, here is how to have many self-referential many-to-many relationships: 尽管我还不知道如何实现“兄弟姐妹”,但这里是如何具有许多自指多对多关系的方法:
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)
basically, for each wanted many-to-many relationship, make the table representing the relationship, then add the relation to your module. 基本上,对于每个想要的多对多关系,创建代表该关系的表,然后将该关系添加到模块中。 You can have two-way relations for each one of them 您可以为每个人建立双向关系
I will edit my answer later when I figure how to make siblings 当我弄清楚如何做兄弟姐妹时,我将编辑答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.