我有3个型号:
class Customer(Model):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
statemented_branch_id = Column(Integer, ForeignKey('branch'))
...
class Branch(Model):
__tablename__ = 'branch'
id = Column(Integer, primary_key=True)
...
class SalesManager(Model):
__tablename__ = 'sales_manager'
id = Column(Integer, primary_key=True)
branches = relationship('Branch', secondary=sales_manager_branches)
表格构造:
sales_manager_branches = db.Table(
'sales_manager_branches',
Column('branch_id', Integer, ForeignKey('branch.id')),
Column('sales_manager_id', Integer, ForeignKey('sales_manager.id'))
)
我希望能够获得Customers
的所有SalesManager
,这意味着所有statemented_branch_id
Branch
SalesManager.branches
的客户branch_alias = aliased(Branch)
custs = Customer.query.join(branch_alias, SalesManager.branches).\
filter(Customer.statemented_branch_id == branch_alias.id)
关系。
我的查询看起来有点像这样:
Customers
这显然不对。
如何获得SalesManager
的所有Customer.query.\
join(Branch).\
join(SalesManager.branches).\
filter(SalesManager.id == 1).all()
?
更新
当我尝试:
*** OperationalError: (OperationalError) ambiguous column name: branch.id u'SELECT
customer.id AS customer_id, customer.statemented_branch_id AS
customer_statemented_branch_id \nFROM customer JOIN branch ON branch.id
customer.statemented_branch_id, "SalesManager" JOIN sales_manager_branches AS
sales_manager_branches_1 ON "SalesManager".id = sales_manager_branches_1.sdm_id JOIN
branch ON branch.id = sales_manager_branches_1.branch_id \nWHERE "SalesManager".id = ?'
(1,)
我得到一个OperationalError:
{{1}}
答案 0 :(得分:7)
我需要在backref
模型中添加SalesManager
,以便SQLAlchemy能够弄清楚如何从SalesManager
转到分支。
class SalesManager(Model):
__tablename__ = 'sales_manager'
id = Column(Integer, primary_key=True)
branches = relationship(
'Branch', secondary=sales_manager_branches, backref="salesmanagers")
构造如下的查询:
Customer.query.\
join(Branch).\
join(Branch.salesmanagers).\
filter(SalesManager.id == 1).all()
答案 1 :(得分:1)
尝试:
SalesManager.query \
.join(Branch) \
.join(Customer) \
.filter(SalesManager.id == 123)
您可能需要通过on
的第二个参数提供显式join
参数,或者您可能需要显式添加映射表 - 但无论哪种情况,您要尝试的是以下内容:
SELECT SM.*
FROM sales_manager SM
JOIN sales_manager_branches SMB
ON SM.id = SMB.sales_manager_id
JOIN branch B
ON SMB.branch_id = B.id
JOIN customer C
ON B.id = C.statemented_branch_id
WHERE -- Conditions go here