2014-01-17 16 views
4

我需要創建一個表名爲朋友,它應該是這樣的:如何創建模型的用戶關係多對多在SQLAlchemy的(蟒蛇,瓶),以自身

朋友:

  • user_id說明
  • friend_id

我試圖從SQL教程要做到這一點鍊金術,但我還沒有找到如何在同一張桌子上建立多對多的關係。

這是我曾嘗試:

# friends table 
# many to many - user - user 
_friends = db.Table('friends', 
    db.Column('user_id', db.Integer, db.ForeignKey('users.id')), 
    db.Column('friend_id', db.Integer, db.ForeignKey('users.id')) 
) 


class User(db.Model, UserMixin): 

    # table name in database 
    __tablename__ = 'users' 

    # primary key for table in db 
    id = db.Column(db.Integer, primary_key=True) 

    # email is unique! 
    email = db.Column(db.String(255), unique=True) 

    # password, max = 255 
    password = db.Column(db.String(255)) 

    # category relation 
    categories = relationship("Category") 

    # cards relation 
    cards = relationship("BusinessCard") 

    # friends 
    friends = db.relationship(
     'User', 
     backref="users", 
     secondary=_friends 
    ) 

它說:

AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship User.friends - there are multiple foreign key paths linking the tables via secondary table 'friends'. 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.

沒有人知道該怎麼做是否正確?

回答

8

您試圖實施的模式是多對多關係的特例。 SQLAlchemy中調用這個鄰接表的關係,我建議您嘗試通過代碼有遵循:

http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#adjacency-list-relationships

的關鍵是「remote_side」 kwarg那裏。

原因如下:您得到的錯誤是因爲您的關聯表('朋友')有兩個指向表'用戶'的外鍵:一列在'user_id'列,另一個在'friend_id'列。 SQLAlchemy試圖根據外鍵自動檢測關係,但是它失敗了,因爲它無法分辨關係走向哪個方向。所以,如果你有一個像這樣

user_id : 1 
friend_id : 2 

的SQLAlchemy不能告訴USER_1是否有user_2作爲一個朋友,或者反之亦然表「朋友」的條目。

如果這似乎令人困惑,那就是。社交網絡意義上的友誼可以是非客觀的,在這種情況下,具有朋友user_2的user_1並不意味着user_2具有user_1作爲朋友;或者它可以是雙射,在這種情況下兩者是等價的。我在這裏展示我的年齡,但前者由Livejournal代表,而後者由Facebook代表。

我不知道如何在SQLAlchemy中實現一種非客觀關係。這是一個醜陋的UNION ALL或類似的東西在MySQL中。

1

您不能直接在2個表格之間建立多對多關係,而必須使用第3個表格。 enter image description here

相關問題