我在代表我的数据库的 sqlalchemy 中有以下 ORM 模式,我希望自动加入来自客户的发票。
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import Column, ForeignKey, Integer, String
Base = declarative_base()
class Customer(Base):
__tablename__ = 'customers'
id = Column(Integer, primary_key=True)
name = Column(String)
address = Column(String)
email = Column(String)
invoices = relationship("Invoice", primaryjoin="Customer.id == Invoice.custid")
class Invoice(Base):
__tablename__ = 'invoices'
id = Column(Integer, primary_key=True)
custid = Column(Integer, ForeignKey("customers.id"))
invno = Column(Integer)
amount = Column(Integer)
如果我使用这个语句:
s = session.query(Customer, Invoice).join(Customer.invoices)
它给了我正确的结果:
SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email, invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM customers JOIN invoices ON customers.id = invoices.custid
但是我想使用 SQL Alchemy 的核心,使用 Select,Join,没有查询,我该怎么做呢?
我试过:
j = Customer.join(Customer.invoices)
stmt = select([Customer,Invoice]).select_from(j)
但不工作,有什么想法吗?
提前致谢。