I have a table defined with relationships and I noticed that even though I don't use joins in my query, the information is still retrieved:
class Employee(Base):
__tablename__ = "t_employee"
id = Column(Identifier(20), Sequence('%s_id_seq' % __tablename__), primary_key=True, nullable=False)
jobs = relationship("EmployeeJob")
roles = relationship("EmployeeRole")
class EmployeeJob(Base):
__tablename__ = "t_employee_job"
id = Column(Integer(20), Sequence('%s_id_seq' % __tablename__), primary_key=True, nullable=False)
employee_id = Column(Integer(20), ForeignKey('t_employee.id', ondelete="CASCADE"), primary_key=True)
job_id = Column(Integer(20), ForeignKey('t_job.id', ondelete="CASCADE"), primary_key=True)
class EmployeeRole(Base):
__tablename__ = "t_employee_role"
id = Column(Integer(20), Sequence('%s_id_seq' % __tablename__), primary_key=True, nullable=False)
employee_id = Column(Integer(20), ForeignKey('t_employee.id', ondelete="CASCADE"), nullable=False)
location_id = Column(Identifier(20), ForeignKey('t_location.id', ondelete="CASCADE"))
role_id = Column(Integer(20), ForeignKey('t_role.id', ondelete="CASCADE"), nullable=False)
session.query(Employee).all() retrieves also the roles and jobs but does so by querying the db for each row.
I have 2 questions about this situation:
1. In terms of performance I guess I should do the join by myself. Am I correct?
2. How do I map a table to a certain data structure? For example, I want to get the list of employees with their roles where each role should be represented by an Array of location ID and role ID e.g. {id:1, jobs:[1,2,3], roles:[[1,1],[1,2],[2,3]]}