how to join 4 or more tables in sequelize?

限于喜欢 提交于 2021-01-07 06:34:44

问题


I am rewriting an app , with existing database using sequelize. I have converted existing table, to models in sequelize as below. I have employee table, and access type model, which has read, write, or both in an admin access. all of these access are tracked for employee in and employee access table. but there is a employee group table also, which keeps track , if employee belongs to a particular group and their access type. how do i query using sequelize , to get particular employee access list from employeeAccess table, and also if it belongs to group and if it does access type of that group. so essentially, need to query by joining 4 tables - employee, employee access, employee group and then access type table.

  1. employee model
    var employee = db.seq.define('Employee',{
        id: { type: db.Sequelize.INTEGER},
        managerId: { type: db.Sequelize.INTEGER}, 
        employee_name: { type: db.Sequelize.STRING} ...
    });
    employee.hasOne(address);
    employee.belongsTo(employee, { foreignKey: 'managerId', as: 'Manager' }); 
  1. address model
    var adress= db.seq.define("Adresss",{
        employee_id: { type: db.Sequelize.INTEGER}...
    });
    address.belongsto(employee); 
  1. accessType model
    var accessType = db.seq.define('AccessType ',{
        id: { type: db.Sequelize.INTEGER},
        type: { type: db.Sequelize.STRING}....
    });
    accessType.hasMany(employeeGroup );
    accessType.hasMany(employeeAccess);
  1. EmployeeGroup model
    var EmployeeGroup = db.seq.define('EmployeeGroup ',{
        id: { type: db.Sequelize.INTEGER},
        access_type_id: { type: db.Sequelize.INTEGER},
        employee_id: { type: db.Sequelize.INTEGER} ...
    });
    EmployeeGroup .belongsto(employee);
    EmployeeGroup .belongsto(accessType ); 
  1. employeeAccess model
    var employeeAccess = db.seq.define('employeeAccess ',{
        id: { type: db.Sequelize.INTEGER},
        access_type_id: { type: db.Sequelize.INTEGER},
        employee_id: { type: db.Sequelize.INTEGER} ...
    });
    employeeAccess.belongsto(employee); 
    employeeAccess.belongsto(accessType ); 

sql

select * from employeeAcess as a 
left outer join employeeGroup as g 
on a.access_type_id = g.access_type_id 
left outer join accesstype as t 
on g.access_type_id = t.id 
where a.employee_id = 1 and g.employee_id = 1; 

回答1:


Try something like this:

const employeeItem = await employee .findById(1, {
  include: [{ 
    model: employeeGroup,
    include: [accessType]
  }, employeeAccess],
  where: {
    '$employeeGroup.access_type_id$': sequelize.col('employeeAccess.access_type_id')
  }
}


来源:https://stackoverflow.com/questions/64947004/how-to-join-4-or-more-tables-in-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!