使用sequelize,我试图更新嵌套属性,但没有成功:
const Product = sequelize.define('product', {
title: { type: Sequelize.STRING },
color: { type: Sequelize.STRING },
});
const User = sequelize.define('user', {
name: { type: Sequelize.STRING },
});
Product.belongsTo(User);
User.hasMany(Product);
// create some data
await User.create({
name: 'foo',
products:[
{ title: 'prod1', color:'blue' },
{ title: 'prod2', color:'red' },
]
},
{ include: [ Product ] }
);
// query data
var data = await sequelize.models.user.findOne({
where: { name:'foo' },
include: [ Product ]
});
// update data
data.products[0].color = 'green';
await data.save();
// result
var data = await sequelize.models.user.findAll({
include: [ Product ]
});在这里,产品的颜色仍然是蓝色。我想知道出了什么问题
edit1:edit1--我需要从模型的“根”更新,因为数据更新来自JSON结构,而包含的模型的数据是这种结构的一部分
发布于 2018-02-23 18:43:54
您需要对update模型的实例调用product:
await data.products[0].update({
color: 'some other color'
});现在,您只是在更改findOne返回的对象的值。当您调用save时,模型的实例还不知道您更改了任何值。
https://stackoverflow.com/questions/48945418
复制相似问题