簡體   English   中英

SQLAlchemy與自引用輔助數據庫的關系

[英]SQLAlchemy relationship with self-referential secondary

我有以下情況:

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=...)

您需要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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM