我正在尝试终止/更新带有续集的嵌套关联。我正在尝试使用upsert
进行此操作,因为我认为这是完成该任务的正确方法。因为我需要使用正确的FK更新第二个嵌套的关联,所以我认为我应该在第一次upsert之后获得插入的记录,但是我不知道该如何实现。
我正在使用Sequelize,我确实读过https://github.com/sequelize/sequelize/pull/8924和https://github.com/sequelize/sequelize/issues/3354,但找不到路。
这些是我的模型定义:
const Languages = sequelize.define('Languages', {
name: {
type: DataTypes.STRING
},
slug: {
type: DataTypes.STRING,
unique: true
}
});
const Projects = sequelize.define('Projects', {
rating: {
type: DataTypes.INTEGER
}
});
Projects.associate = function(models) {
Projects.hasMany(models.ProjectImages);
};
const ProjectImages = sequelize.define('ProjectImages', {
img: {
type: CustomTypes.STRING
}
});
ProjectImages.associate = models => {
ProjectImages.hasMany(models.ProjectImagesTranslations);
};
const ProjectImagesTranslations = sequelize.define('ProjectImagesTranslations', {
title: {
type: DataTypes.STRING
}
});
ProjectImagesTranslations.associate = function(models) {
models.Languages.hasMany(ProjectImagesTranslations, {
foreignKey: 'language',
sourceKey: 'slug'
});
};
现在我要保存一个项目的数据,其中包括一些图像,每个图像都包含一些翻译。
Projects.update(req.body, {
where: {
id: req.params.id
}
}).then(result => {
// Add fk to new items
req.body.ProjectImages.forEach(item => {
item['ProjectId'] = req.params.id;
});
// For each object in ProjectImages store an upsert in an array
// to execute it later with Promise.all()
let ProjectImagesPromises = [];
req.body.ProjectImages.map(item => {
ProjectImagesPromises.push(
ProjectImages.upsert(item, {
where: {
id: item.id
},
returning: true
}).then(result => {
req.body.ProjectImagesTranslations.forEach(item => {
item['ProjectImageId'] = /* NEED THE ID OF THE NEW ProjectImage HERE */;
});
// For each object in ProjectImagesTranslations store
// an upsert in an array to execute it later with Promise.all()
// [...]
})
);
});
Promise.all(ProjectImagesPromises).then(() => {
// Find all data and return it
});
});
如何获取ProjectImages.upsert()
的新插入实例的ID?