我正在使用node / Express,Sequelize和MySQL。
我有一个Project
模型,该模型与ProjectImages
具有hasMany关系。我正在添加/更新特定项目的图像中的某些行。
这是我的Project
模型:
module.exports = (sequelize, DataTypes) => {
const Projects = sequelize.define(
'Projects',
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
title: {
type: DataTypes.STRING,
},
ArticleId: {
type: DataTypes.INTEGER,
},
timestamp: {
type: DataTypes.DATE,
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
},
},
{}
);
Projects.associate = function(models) {
Projects.hasMany(models.ProjectImages);
models.ProjectImages.belongsTo(Projects);
};
return Projects;
};
它具有以下数据:
{
"Projects": [
{
"id": 1,
"title": "First project",
"ArticleId": 1,
"timestamp": "Sat Mar 12 2016 16:12:09 GMT-0800 (PST)",
"rating": 2
}
]
}
这是ProjecImages
:
module.exports = (sequelize, DataTypes) => {
const ProjectImages = sequelize.define(
'ProjectImages',
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
img: {
type: DataTypes.STRING,
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
},
updatedAt: {
allowNull: false,
type: DataTypes.DATE,
defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
},
},
{}
);
return ProjectImages;
};
它具有以下数据:
{
"ProjectImages": [
{
"id": 1,
"img": "/media/images/article-image-1.jpg",
"createdAt": "2018-07-22T15:15:16.000Z",
"updatedAt": "2018-07-22T15:15:16.000Z",
"ProjectId": 1
},
{
"id": 2,
"img": "/media/images/article-image-2.jpg",
"createdAt": "2018-07-22T15:15:16.000Z",
"updatedAt": "2018-07-22T15:15:16.000Z",
"ProjectId": 1
}
]
}
现在,我在前端编辑ProjectImages:我用新图像更新第一个元素,删除第二个元素,然后添加新图像:
{
"ProjectImages": [
{
"id": 1,
"img": "/media/images/article-image-3.jpg",
"createdAt": "2018-07-22T15:09:41.000Z",
"updatedAt": "2018-07-22T15:09:41.000Z",
"ProjectId": 1
},
{
"img": "/media/images/article-image-4.jpg",
"ProjectId": 1,
"imgFile_1": ""
}
]
}
我知道如何使用upsert
在Sequelize中进行更新/创建:
ProjectImages.forEach((element) => {
model.upsert(element, {
where: {
id: element.id,
},
});
});
如果元素的ID存在,则此元素将更新,如果ID不存在,则创建一个新元素。但是...如何删除其他元素?有没有办法告诉Sequelize同步具有特定ID的表的所有元素?