简体   繁体   中英

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?

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
department.getEmployees({where: {manager: true}})

change this code with this.

department.getEmployees(      
  include:{
    model: employeedepartments, // your employee departments model name
    {where: {manager: true},      
    required:true, 
  }
})

You have to just add include in your query

I found a very simple answer myself after searching a while.

When using belongsToMany Sequelize does use a join to get data from the second table (I knew that).

I had the option to use the following syntax:

department.getEmployees({where: {'$employeeDepartments.manager$': true}})

I found that from a page on google but unfortunately I lost the url. Maybe this helps someone with a similar problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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