我有两张桌子
class Department(Model):
id = Column(Integer, primary_key=True)
employees = relationship('Employee', backref='department')
class Employee(Model):
id = Column(Integer, primary_key=True)
name = Column(String)
department_id = Column(Integer, ForeignKey('department.id'))
email_addresses = relationship('EmailAddress', backref='employee')
class EmailAddress(Model):
id = Column(Integer, primary_key=True)
value = Column(String)
employee_id = Column(Integer, ForeignKey('employee.id'))
现在我需要找到所有拥有电子邮件地址为X的员工的部门。
当允许每位员工只有一个电子邮件地址时返回(因此他们email_address = Column(String)
我使用了此代码,但我不确定如何将其扩展为使用多封电子邮件:
session.query(Department).filter(
Employee.email_address==request.args['email']
).outerjoin((Employee, Department.employees))
答案 0 :(得分:1)
您可以使用any()方法的关系。这段代码应该这样做:
session.query(Department).filter(
Employee.email_address.any(value=request.args['email'])
).outerjoin((Employee, Department.employees))
答案 1 :(得分:1)
你可以使用这样的任何():
department1 = Department()
department2 = Department()
DBSession.add(department1)
DBSession.add(department2)
employee = Employee()
employee.email_addresses.append(EmailAddress(employee.id, 'e@mail.com'))
DBSession.add(employee)
department1.employees.append(employee)
DBSession.flush()
print(DBSession.query(Department).filter(Department.employees.any(Employee.email_addresses.any(EmailAddress.value == 'e@mail.com'))).all())
请参阅this gist以获取完整示例。