我正在尝试使用SQLAlchemy上的声明来实现自引用的多对多关系.
这种关系代表两个用户之间的友谊.在线我发现(在文档和谷歌中)如何建立一个自我参照的m2m关系,在某种程度上角色是有区别的.这意味着在这个m2m关系中,UserA例如是UserB的老板,所以他将他列为"下属"属性或者你有什么.同样,UserB在'上级'下列出UserA.
这没有问题,因为我们可以用这种方式声明一个backref到同一个表:
subordinates = relationship('User', backref='superiors')
Run Code Online (Sandbox Code Playgroud)
当然,那里的'上级'属性在课堂上并不明确.
无论如何,这是我的问题:如果我想反馈到我正在调用backref的相同属性怎么办?像这样:
friends = relationship('User',
secondary=friendship, #this is the table that breaks the m2m
primaryjoin=id==friendship.c.friend_a_id,
secondaryjoin=id==friendship.c.friend_b_id
backref=??????
)
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为如果A和B交朋友关系角色是相同的,如果我调用B的朋友,我应该得到一个包含A的列表.这是完整的问题代码:
friendship = Table(
'friendships', Base.metadata,
Column('friend_a_id', Integer, ForeignKey('users.id'), primary_key=True),
Column('friend_b_id', Integer, ForeignKey('users.id'), primary_key=True)
)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
friends = relationship('User',
secondary=friendship,
primaryjoin=id==friendship.c.friend_a_id,
secondaryjoin=id==friendship.c.friend_b_id,
#HELP NEEDED HERE
)
Run Code Online (Sandbox Code Playgroud)
对不起,如果这是太多的文字,我只想尽可能明确地用这个.我似乎无法在网上找到任何参考资料.