2013-07-10 96 views
11

我想創建一個跨越3個表的關係,但我無法完全弄清楚語法。跨多個表的SQLAlchemy關係

我有3個表TableATableBTableC,我試圖模型之間的關係是:

TableA.my_relationship = relationship(
    'TableC', 
    primaryjoin='and_(TableA.fk == TableB.pk, TableB.fk == TableC.pk)', 
    viewonly=True 
) 

,這樣就TableA一個實例,我可以做instance_of_a.my_relationship得到TableC記錄這是間接相關與instance_of_a

回答

15
from sqlalchemy import * 
from sqlalchemy.orm import * 
from sqlalchemy.ext.declarative import declarative_base 

Base = declarative_base() 

class A(Base): 
    __tablename__ = 'a' 

    id = Column(Integer, primary_key=True) 
    b_id = Column(Integer, ForeignKey('b.id')) 

    # method one - put everything into primaryjoin. 
    # will work for simple lazy loads but for eager loads the ORM 
    # will fail to build up the FROM to correctly include B 
    cs = relationship("C", 
       # C.id is "foreign" because there can be many C.ids for one A.id 
       # B.id is "remote", it sort of means "this is where the stuff 
       # starts that's not directly part of the A side" 
       primaryjoin="and_(A.b_id == remote(B.id), foreign(C.id) == B.c_id)", 
       viewonly=True) 

    # method two - split out the middle table into "secondary". 
    # note 'b' is the table name in metadata. 
    # this method will work better, as the ORM can also handle 
    # eager loading with this one. 
    c_via_secondary = relationship("C", secondary="b", 
         primaryjoin="A.b_id == B.id", secondaryjoin="C.id == B.c_id", 
         viewonly=True) 
class B(Base): 
    __tablename__ = 'b' 

    id = Column(Integer, primary_key=True) 
    c_id = Column(Integer, ForeignKey('c.id')) 

class C(Base): 
    __tablename__ = 'c' 
    id = Column(Integer, primary_key=True) 

e = create_engine("sqlite://", echo=True) 
Base.metadata.create_all(e) 

sess = Session(e) 

sess.add(C(id=1)) 
sess.flush() 
sess.add(B(id=1, c_id=1)) 
sess.flush() 
sess.add(A(b_id=1)) 
sess.flush() 

a1 = sess.query(A).first() 
print(a1.cs) 

print(a1.c_via_secondary) 
+0

由於某種原因,一種關係定義方法是否比另一種優先?在方法二中,「secondary」的明確引用在方法一中直觀上似乎比複雜的「primaryjoin」str更清晰......但方法一似乎可能更強大。 – Russ

+0

這是一種奇怪的類型,因此就次要而言,這並不是最初打算如何使用「次要」的,例如,它預計FK將全部在中間。我不確定這種「次要」關係是否真的能夠正確保持,例如它可能需要viewonly = True。 ORM在構建諸如緊急加載之類的東西時也會做出不同的選擇,在這方面,「次要」版本可能做出更好的決定,因爲它知道FROM子句中有一個額外的表。 – zzzeek

+0

確認,加入只有第二個加載只能工作,第一個不能正確地建立FROM從 – zzzeek