![](/img/trans.png)
[英]Sqlalchemy: self-referential many-to-many relationship with extra column in relationship table
[英]SQLAlchemy - Self referential Many-to-many relationship with extra column
我有一個代表用戶的模型,我想在代表他們是朋友的用戶之間建立關系。 我的帶有關聯表和列出所有朋友的方法的功能模型如下所示
friendship = db.Table('friend',
db.Column('id', db.Integer, primary_key=True),
db.Column('fk_user_from', db.Integer, db.ForeignKey('user.id'), nullable=False),
db.Column('fk_user_to', db.Integer, db.ForeignKey('user.id'), nullable=False)
)
class User(db.Model):
...
...
friends = db.relationship('User',
secondary=friendship,
primaryjoin=(friendship.c.fk_user_from==id),
secondaryjoin=(friendship.c.fk_user_to==id),
backref = db.backref('friend', lazy = 'dynamic'),
lazy = 'dynamic')
def list_friends(self):
friendship_union = db.select([
friendship.c.fk_user_from,
friendship.c.fk_user_to
]).union(
db.select([
friendship.c.fk_user_to,
friendship.c.fk_user_from]
)
).alias()
User.all_friends = db.relationship('User',
secondary=friendship_union,
primaryjoin=User.id==friendship_union.c.fk_user_from,
secondaryjoin=User.id==friendship_union.c.fk_user_to,
viewonly=True)
return self.all_friends
問題是我需要在確認之前實現詢問好友和狀態待定(就像你從 Facebook 知道的那樣),所以需要在好友表中添加一個額外的列。 根據SQLAlchemy 教程,我應該創建一個關聯對象,但如何使其再次自引用?
或者是否可以將此列添加到我當前的朋友表中並以某種方式訪問和更改狀態值?
謝謝
您所需要的只是在您的表中添加 primaryjoin 並在 Friendship 表中創建兩個外鍵,“primary_key”。 你還需要把友誼當成一個班級。
class Friendship(db.Model):
__tablename__ = 'friend'
fk_user_from = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
fk_user_to = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
extra_field = db.Column(db.Integer)
class User (db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
user_to = db.relationship('Friendship',backref='to', primaryjoin=id==Friendship.fk_user_to)
user_from = db.relationship('Friendship',backref='from', primaryjoin=id==Friendship.fk_user_from )
要添加一個朋友,您需要像這樣定義 Friendship:
friend = Friendship(extra_field=0 , to=me , from=my_friend)
我已經回答了一個類似的問題,該問題解決了與關聯對象的自引用多對多關系。
見https://stackoverflow.com/a/62281276/9387542
另外,如果您只是在尋找建立友誼模型,我建議您與來自https://stackoverflow.com/a/7317251/9387542的模型建立多對多關系
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.