【发布时间】:2021-12-27 14:13:17
【问题描述】:
我有一个产品表和产品图片表。
module.exports = (sequelize, DataTypes) => {
const Product = sequelize.define("product", {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
name: { type: STRING },
price: { type: STRING }
}, {
timestamps: false,
freezeTableName: true,
})
Product.associate = function (models) {
Product.hasMany(models.product_image, { as: 'images' });
};
return Product;
}
module.exports = (sequelize, DataTypes) => {
const ProductImages = sequelize.define("product_image", {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
productId: { type: INTEGER},
title: { type: STRING },
url: { type: STRING }
}, {
timestamps: false,
freezeTableName: true,
})
return ProductImages;
}
我可以通过将模型包含在来自以下有效负载的 create 方法中,在单个语句中创建产品和产品图像整体
{
"name": "Product 1",
"price": "10.00",
"images": [
{
"title": "image 1",
"url": "url 1 here"
},
{
"title": "image 2",
"url": "url 2 here"
}
]
}
db.product.create({
name: body.name,
price: body.price,
images: body.images
},
{
include: [
{
model: db.product_images,
as: 'images'
}
]
}
).then(product => {\\ITS WORKED FINE. UPDATED BOTH TABLES WITH DETAILS
但我需要根据以下有效负载部分更新产品和图像详细信息。我可以更新产品详细信息。但是图像表没有更新
{
"id": 1,
"price": "55.00",
"images": [
{
"id": 1,
"title": "image 11111111",
},
{
"id": 2,
"url": "url 222222222 here"
}
]
}
let product = {}
product.id = body.id;
if(body.name) product.name = body.name
if(body.price) product.price = body.price
let productImages = []
body.images.forEach(image=>{
let imageItem = {};
imageItem.id = image.id;
if(image.title) imageItem.title = image.title
if(image.url) imageItem.url = image.url
productImages.push(imageItem);
});
if(productImages.length > 0) product.images = productImages
console.log(product);//GOT CORRECT RESULT HERE WITH ONLY UPDATED DETAILS
db.product.update(product,
{where: {id: body.id}},
{
include:[
{
model: db.product_images,
as: 'images'
}
]
}
).then(rowsUpdated=> {
//UPDATED ONLY THE PRODUCT TABLE
})
【问题讨论】: