使用Sequelize更新关联表数据的工作示例



这是我的型号:

var Vote = sequelize.define('vote', {
title: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.TEXT
}
});
var Choice = sequelize.define('choice', {
choiceTitle: {
type: Sequelize.STRING,
allowNull: false
},
count: {
type: Sequelize.INTEGER,
length: 6
}
});
Choice.belongsTo(Vote);
Vote.hasMany(Choice, {onUpdate: 'cascade'});

以下是使用"store()"的"vote"参数更新"votes"表(包括相关的"choices"表)的代码,如果可能的话,该参数已经是vote的对象,更新的值包括应用程序中的"choice"。

store(vote, callback) {
return Vote.findById(vote.id, {
include: [
{
model: Choice,
as: 'choices'
}
]
}).then(function(resVote) {
resVote.choices[0].updateAttributes({count: 120}) // just to test if at least it gets written to db
.then(function(res) {
callback(null, res);
}).catch((err) => callback(err, null));
});
},

仅供参考:在代码中,我只是将特定选择的一个属性设置为120,只是为了看看它是否会被写在postgres数据库中,而且,hooray,这是有效的(感谢Jan Aagaard关于使用Sequelize更新关联模型中的属性以至少更新关联表的回复)。

我在Sequelize的文档中并没有真正找到解决方案(至少他们有一些)。当我尝试"save()"、"update()"或"upstart()"直接投票时,如果允许null,它只会创建一个带有空字段的全新行,如果不允许null,则会失败。

建议用什么方法更新表的所有(更改的)字段,如果可能的话,还更新Sequelize中的关联表?如果这个问题有点基础,我很抱歉,但我现在很困,没有找到这个任务的明确答案。

您可以将includeobj传递给creates(请参阅http://sequelize.readthedocs.io/en/v3/docs/associations/)但你似乎无法通过更新做到这一点。

我认为您想要做的是使用Sequelize提供的关系访问器获取相关记录,并更新这些实例:

Vote.findById(vote.id)
.then(function(vote) {
return vote.getChoices()
})
.then(function(choices) {
return choices[0].update({ count: 120 })
})
.then(function(choice) {
callback(null, choice);
})
.catch(function(err) {
callback(err);
});
(I realise this means you lose the join and end up with two separate queries, but I can't think another way of doing this just now)

最新更新