我遇到了Sequelize的问题。 我在联接表中有2个具有附加属性的模型:
Project.belongsToMany(models.User, {
foreignKey: 'projectId',
as: 'users',
through: models.ProjectUser
});
User.belongsToMany(models.Project, {
foreignKey: 'userId',
as: 'projects',
through: models.ProjectUser
});
module.exports = (sequelize, DataTypes) => {
const ProjectUser = sequelize.define('ProjectUser', {
leader: DataTypes.BOOLEAN,
manager: DataTypes.BOOLEAN
}, {});
ProjectUser.associate = function(models) {
// associations can be defined here
};
return ProjectUser;
};
在我的控制器中,我使用setUsers([])来确保1个项目中没有重复的记录:
if (updateProject.users.length !== 0) {
updatedProject.setUsers([]);
updateProject.users.forEach(user => {
updatedProject.addUser(user.userId, { through: { leader: user.leader, manager: user.manager }});
});
当我插入具有与以前相同ID的新记录时,会发生问题。例如:
[ { userId: 1, leader: 0, manager: 0 },
{ userId: 2, leader: 1, manager: 1 } ]
然后
[ { userId: 1, leader: 0, manager: 0 },
{ userId: 2, leader: 1, manager: 1 },
{ userId: 3, leader: 0, manager: 0 } ]
,结果仅是连接表中的userId 3。从终端:
Executing (default): DELETE FROM `ProjectUsers` WHERE `projectId` = 1 AND `userId` IN (1, 2)
Executing (default): UPDATE `ProjectUsers` SET `leader`=?,`manager`=?,`updatedAt`=? WHERE `projectId` = ? AND `userId` = ?
Executing (default): UPDATE `ProjectUsers` SET `leader`=?,`manager`=?,`updatedAt`=? WHERE `projectId` = ? AND `userId` = ?
Executing (default): INSERT INTO `ProjectUsers` (`leader`,`manager`,`createdAt`,`updatedAt`,`projectId`,`userId`) VALUES (false,false,'2019-07-04 17:57:29','2019-07-04 17:57:29',1,3);
那么,使用setUsers([])时我错了吗?