Reputation: 193
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?
Upvotes: 3
Views: 1171
Reputation: 193
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.
Upvotes: 0
Reputation: 2250
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
Upvotes: 4
Reputation: 470
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
Upvotes: 2