我有以下情况:
class A(Base):
a_string = Column(String)
class B(Base):
id = Column(Integer, primary_key=True)
class C(Base):
b_id = Column(Integer, ForeignKey(B.id))
value = Column(String)
我需要执行以下查询:
SELECT c2.*
FROM a
JOIN c c1 on c1.value = a.a_string
JOIN c c2 on c2.b_id = c1.b_id
问题是我需要在模型A内部的关系中进行上述查询。例如:
class A(Base):
a_string = Column(String)
c_list = relationship('C', secondary=...)
答案 0 :(得分:1)
为了自我加入,您需要C的别名:
In [3]: c_to_c = aliased(C.__table__)
然后,您可以定义主要和次要连接以满足您的需要。这种关系应该只能查看:
In [4]: A.c_list = relationship(
...: C, secondary=c_to_c,
...: primaryjoin=A.a_string == c_to_c.c.value,
...: secondaryjoin=C.b_id == c_to_c.c.b_id,
...: viewonly=True
...: )
然后,您可以验证您是否可以使用加入的预先加载:
In [5]: print(session.query(A).options(joinedload(A.c_list)))
SELECT a.id AS a_id, a.a_string AS a_a_string, c_1.id AS c_1_id, c_1.b_id AS c_1_b_id, c_1.value AS c_1_value
FROM a LEFT OUTER JOIN (c AS c_2 JOIN c AS c_1 ON c_1.b_id = c_2.b_id) ON a.a_string = c_2.value