Search code examples
javascriptmysqlsequelize.jshas-and-belongs-to-many

filter Sequelize belongsToMany get<Association> association table


I am working with Sequelize 4.37.10 and it works great. Unfortunately the documentation is not perfect in my opinion. So it lacks a bit of describing the belongsToMany possibilities.

I have the following problem:

I defined my tables like this:

const Department = db.define('department', {
  name: {type: Sequelize.STRING, allowNull: false},
  shortName: {type: Sequelize.STRING, allowNull: false}
})

const Employee = db.define('employee', {
  title: {type: Sequelize.STRING},
  name: {type: Sequelize.STRING, allowNull: false},
  surname: {type: Sequelize.STRING, allowNull: false},
  .
  .
  role: {type: Sequelize.STRING}
})

Then I associated the tables like this:

const EmployeeDepartments = db.define('employeeDepartments', {
  manager: {type: Sequelize.BOOLEAN, allowNull: false}
})

Department.belongsToMany(Employee, {through: EmployeeDepartments})
Employee.belongsToMany(Department, {through: EmployeeDepartments})

Now i want to get all department employees with the manager field set to true. The creation was no problem, but the select is a problem for me.

I tried the following with no luck:

department.getEmployees({where: {manager: true}})

I also thought of scopes but I don't know how to design that properly.

Can you help me with that?


Solution

  • Funnily, I was just looking for the exact same thing, and the only result was your question from a few hours ago...

    I solved it by now, what you need is the following:

    department.getEmployees({ through: { where: { manager: true } } })
    

    You can also get all employees of a department of which you only have the id:

    const department = Department.build( { id: departmentId } );
    // proceed as above