简体   繁体   English

SQLAlchemy - 查询多个表并返回嵌套对象

[英]SQLAlchemy - querying multiple tables and returning nested objects

Suppose we have a simple one-to-many relationship between Company and Employee, is there a way to query all companies and have a list of employees in the attribute of each company?假设我们在 Company 和 Employee 之间有一个简单的一对多关系,有没有办法查询所有公司并在每个公司的属性中都有一个员工列表?

class Company(Base):
    __tablename__ = 'company'

    id = Column(Integer, primary_key=True)
    name = Column(String)


class Employee(Base):
    __tablename__ = 'employee'

    id = Column(Integer, primary_key=True)
    first_name = Column(String)
    last_name = Column(String)
    company_id = Column(Integer, ForeignKey(Company.id))

I'm looking for something like this:我正在寻找这样的东西:

>>> result = db.session.query(Company).join(Employee).all()
>>> result[0].Employee
[<Employee object at 0x...>, <Employee object at 0x...>]

The size of result should be same as the number of rows in company table.结果的大小应与公司表中的行数相同。

I tried the following and it gives tuple of objects (which makes sense) instead of nice parent / child structure:我尝试了以下方法,它提供了对象元组(这是有道理的)而不是好的父/子结构:

>>> db.session.query(Company, Employee).filter(Company.id = Employee.company_id).all()

It's not hard to convert this into my desired object structure but just wanted to see if there's any shortcut.将其转换为我想要的对象结构并不难,只是想看看是否有任何捷径。

You have to configure the relationship in the parent class:您必须在父类中配置关系:

class Company(Base):
    __tablename__ = 'company'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    employees = relationship('Employee', lazy='joined') # <<< Add this line

Then you can query it without a join:然后你可以在没有连接的情况下查询它:

companies = session.query(Company).all()
print(companies[0].employees)

Documentation: https://docs.sqlalchemy.org/en/13/orm/loading_relationships.html文档: https : //docs.sqlalchemy.org/en/13/orm/loading_relationships.html

You could do something like this:你可以这样做:

class Company(Base):
    __tablename__ = 'company'

    id = Column(Integer, primary_key=True)
    name = Column(String)

    employees = db.session.query(Company, Employee).filter(Company.id = self.id).all()
    self.employee_list = ['{0} {1}'.format(c.first_name, c.last_name) for c in employees]

Then you could access a employee name with Company.employee_list[0]然后您可以使用Company.employee_list[0]访问员工姓名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM