我需要创建一个名为friends 的表,它应该如下所示:
friend :
- 用户编号
- friend_id
我试图通过 SQLALchemy 的教程来做到这一点,但我还没有找到如何为同一个表建立多对多关系。
这是我尝试过的:
# 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.
有谁知道如何正确地做到这一点?
最佳答案
您尝试实现的模式是多对多关系的特例。 SQLAlchemy 将此称为邻接列表关系,我建议尝试按照那里的代码进行操作:
http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#adjacency-list-relationships
关键是那里的 'remote_side' kwarg。
原因如下:您得到的错误是因为您的关联表(“ friend ”)有两个指向表“用户”的外键:一个在“user_id”列上,一个在“friend_id”列上。 SQLAlchemy 尝试根据外键自动检测关系,但它失败了,因为它无法判断关系的方向。因此,如果您在表“ friend ”中有一个条目,就像这样
user_id : 1
friend_id : 2
SQLAlchemy 无法判断 user_1 是否有 user_2 作为 friend ,反之亦然。
如果这看起来令人困惑,那确实是。社交网络意义上的友谊可以单射,在这种情况下,user_1 有 friend user_2 并不意味着 user_2 有 user_1 作为 friend ;或者它可以是双射,在这种情况下两者是等价的。我在这里显示我的年龄,但前者以 Livejournal 为代表,而后者以 Facebook 为代表。
我不知道如何在 SQLAlchemy 中实现单射关系。这是 MySQL 中丑陋的 UNION ALL 或类似的东西。
关于python - 如何在 SQLAlchemy(python,flask)中为模型用户自身创建多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21189559/