我在这两个模型之间的MSQL表中有多对多的关系:
- Venue – Representing a venue which can have multiple owners (employees)
- Employee – Representing an employee which can be either a ceo or sales employee or whatsoever.
我正在使用sequelize来建立这样的关系:
关系员工>地点
Employee.associate = function (models) {
models.Employee.belongsToMany(models.Venue, { through: 'EmployeeVenues' })
}
关系地点>雇员
Venue.associate = function (models) {
models.Venue.belongsToMany(models.Employee, { through: 'EmployeeVenues' })
}
Sequelize docs
According to the 07001 it will create a new model called EmployeeVenues with the equivalent foreign keys employee_id and venue_id. Defining through is required. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups. This will add methods getVenues, setVenues, addVenue, addUsers to Employee.
这是正确的工作,当我启动我的Sequelize时,它会创建一个名为EmpoyeeVenues的新表,并使用正确的外键作为复合键.但是,当我查询getVenues时,它不会返回预期的输出.相反,它也返回相关的表值,这是我不想要的.
查询以获取属于id等于1的员工的所有场所
router.get('/api/v1/users/:employee_id/venues', (request, response) => {
var employeeId = request.params.employee_id;
models.Employee.findOne({
where: {id: employeeId}
}).then((employee) => {
if(!employee) { return response.status(400).send("Employee doesnt have a venue registered yet.")}
var venues = employee.getVenues().then((venues) => {
response.status(200).send(venues);
})
})
});
响应结果
[
{
"id": 1,
"capacity": "11",
"venue_name": "Club Fix",
"venue_description": "Club in Tilburg",
"EmployeeVenues": {
"employee_id": 1,
"venue_id": 1
}
},
{
"id": 2,
"capacity": "400",
"venue_name": "Club Vie",
"venue_description": "Club in Rotterdam",
"EmployeeVenues": {
"employee_id": 1,
"venue_id": 2
}
}
]
题
Why is EmployeeVenues included in this query provided by Sequelize? And How can I prevent EmployeeVenues to be included in the response?
更新
According to a issue on the Sequelize github page which was made in 2014 there is a solution that works
https://github.com/sequelize/sequelize/issues/2143
User.find({
where: {id: userId}, attributes: userFields,
include: [
{model: db.Role, attributes: roleFields, through: {attributes: []}}
]
});
但它与Sequelize文档中的文档版本不匹配,该文档是最新的,至少它应该是.
User.findAll({
include: [{
model: Project,
through: {
attributes: ['createdAt', 'startedAt', 'finishedAt'],
where: {completed: true}
}
}]
});
甚至在reference documentation:简单说明
user.getPictures() // gets you all pictures
最佳答案 更新
According to a issue on the Sequelize github page which was made in 2014 there is a solution that works
https://github.com/sequelize/sequelize/issues/2143
User.find({
where: {id: userId}, attributes: userFields,
include: [
{model: db.Role, attributes: roleFields, through: {attributes: []}}
]
});
但它与Sequelize文档中的文档版本不匹配,该文档是最新的,至少它应该是.
User.findAll({
include: [{
model: Project,
through: {
attributes: ['createdAt', 'startedAt', 'finishedAt'],
where: {completed: true}
}
}]
});
或者甚至在reference documentation:上简单说明
user.getPictures() // gets you all pictures