我试图在 SQLAlchemy 中的单个查询中连接三个表,但无法这样做。 到目前为止我已经做到了:-
Test.query.join(Test.sections).join(QuestionSection.section).all()
我知道这是错误的,但我试图在单个查询中完成它。
这是我的表格:-
问题部分型号:-
class QuestionSection(Dictifiable, db.Model):
__tablename__ = 'question_section'
section_id = Column(Integer, ForeignKey('section.id'), primary_key=True)
question_id = Column(Integer, ForeignKey('question.id'), primary_key=True)
question = db.relationship('Question', backref='question_section')
section = db.relationship('Section', backref='question_section')
节表:-
class Section(Dictifiable, db.Model):
__tablename__ = 'section'
id = Column(Integer, Sequence('section_id_seq'), primary_key=True)
test_id = Column(Integer, ForeignKey('test.id'))
name = Column(String(50))
test = relationship("Test", back_populates="sections")
questions = db.relationship('Question',
secondary='question_section')
和测试表:-
id = Column(Integer, Sequence('test_id_seq'), primary_key=True)
name = Column(String(50))
sections = relationship("Section", back_populates="test")
tests = relationship("Corporate", secondary='corporate_test',
back_populates='tests')
最佳答案
我明白我做错了什么,我应该这样加入:-
Test.query.join(Test.sections).join(QuestionSection, QuestionSection.section_id == Section.id).all()
关于mysql - 对单个查询中的多个 Join 感到困惑,Sqlalchemy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205136/