2013-06-22 77 views
5

Flask-SQLAlchemy給出了一個example關於如何創建多對多關係。它在兩張不同的表格之間完成。在一張桌子上創建多人到多人

是否可以在同一張桌子上創建多對多關係?例如,一個姐妹可以有很多姐妹,也會有很多姐妹。我曾嘗試:

girl_sister_map = db.Table('girl_sister_map', 
         db.Column('girl_id', 
           db.Integer, 
           db.ForeignKey('girl.id')), 
         db.Column('sister_id', 
           db.Integer, 
           db.ForeignKey('girl.id'))) 

class Girl(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String) 
    sisters = db.relationship('Girl', 
           secondary=girl_sister_map, 
           backref=db.backref('othersisters', lazy='dynamic')) 

但是,當我嘗試將妹妹添加到一個女孩,我得到:

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Girl.sisters - there are multiple foreign key paths linking the tables via secondary table 'girl_sister_map'. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference from the secondary table to each of the parent and child tables.

這可能嗎?我應該怎麼做呢?

回答

9

您正在嘗試構建所謂的adjacency list。那就是你有一張帶有外鍵的表格。

在你的具體情況下,它是一個self referencial many to many relationship

這在SQLAlchemy中是受支持的,您將通過上一個鏈接發現它。該文件包含幾個例子。

基本上,您將需要參數primaryjoinsecondaryjoin來確定如何加入表格。直接從文檔:

Base = declarative_base() 

node_to_node = Table("node_to_node", Base.metadata, 
    Column("left_node_id", Integer, ForeignKey("node.id"), primary_key=True), 
    Column("right_node_id", Integer, ForeignKey("node.id"), primary_key=True) 
) 

class Node(Base): 
    __tablename__ = 'node' 
    id = Column(Integer, primary_key=True) 
    label = Column(String) 
    right_nodes = relationship("Node", 
         secondary=node_to_node, 
         primaryjoin=id==node_to_node.c.left_node_id, 
         secondaryjoin=id==node_to_node.c.right_node_id, 
         backref="left_nodes" 
    ) 
相關問題