Many to many 炼金术中的多对多自指关系
我试图在sqlalchemy中建立一个自引用的多对多关系(这意味着行可以有许多父行和许多子行),如下所示:Many to many 炼金术中的多对多自指关系,many-to-many,sqlalchemy,relationship,self-reference,Many To Many,Sqlalchemy,Relationship,Self Reference,我试图在sqlalchemy中建立一个自引用的多对多关系(这意味着行可以有许多父行和许多子行),如下所示: Base = declarative_base() class Association(Base): __tablename__ = 'association' prev_id = Column(Integer, ForeignKey('line.id'), primary_key=True) next_id = Colum
Base = declarative_base()
class Association(Base):
__tablename__ = 'association'
prev_id = Column(Integer, ForeignKey('line.id'), primary_key=True)
next_id = Column(Integer, ForeignKey('line.id'), primary_key=True)
class Line(Base):
__tablename__ = 'line'
id = Column(Integer, primary_key = True)
text = Column(Text)
condition = Column(Text)
action = Column(Text)
next_lines = relationship(Association, backref="prev_lines")
class Root(Base):
__tablename__ = 'root'
name = Column(String, primary_key = True)
start_line_id = Column(Integer, ForeignKey('line.id'))
start_line = relationship('Line')
但我得到了以下错误:
sqlalchemy.exc.ArgumentError:无法确定父级之间的联接条件/
关系行上的子表。下一行。指定“primaryjoin”表达式
N如果存在“secondary”,则还需要“secondaryjoin”
你知道我该如何补救吗?你只需要:
prev_lines = relationship(
Association,
backref="next_lines",
primaryjoin=id==Association.prev_id)
由于这指定了next_行
back引用,因此不需要有next_行
关系
您也可以使用关系的
remote\u-side
参数来实现这一点:我尝试了以下方法:next\u-lines=relationship(Association,backref=“prev\u-lines”,primaryjoin=id==Association.next\u-id)prev\u-lines=relationship(Association,backref=“next\u-lines”,primaryjoin=id==Association.prev\u-id)现在它不会产生任何错误。这是正确的解决方案吗?还是会产生其他问题?