问题
Let's say I have the following simple model:
var Foo = sequelize.define('Foo', {
bar: Sequelize.STRING,
});
And the table Foos in the database has a record:
id bar
--- ---
1 abc
In order to update this record I could do the following:
Foo.findById(1).then(function(foo) {
foo.bar = 'xyz';
foo.save();
});
Now I have found another way to update the record without having to find it form the database:
var foo = Foo.build({ id: 1, bar: 'xyz' });
foo.isNewRecord = false; // makes save use UPDATE instead of INSERT INTO
foo.save();
This is perfect for my use case, but I'm wondering if I'm breaking anything in sequelize.
回答1:
There is a parameter in the build function that takes an object called options. options has an attribute isNewRecord that defaults to true. If you set this to false and use update() it will update the existing record after you set the primary key.
let instance = await db.Model.build({}, {isNewRecord: false});
const result = await instance.update({
id: instanceId,
column : newValue
});
source
来源:https://stackoverflow.com/questions/41286833/sequelize-using-build-to-update-a-record