Sequelize:使用 build 更新记录 [英] Sequelize: using build to update a record

查看:26
本文介绍了Sequelize:使用 build 更新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下简单模型:

var Foo = sequelize.define('Foo', {酒吧:Sequelize.STRING,});

并且数据库中的表Foos有一条记录:

id 栏--- ---1个ABC

为了更新此记录,我可以执行以下操作:

Foo.findById(1).then(function(foo) {foo.bar = 'xyz';foo.save();});

现在我找到了另一种方法来更新记录,而不必从数据库中找到它:

var foo = Foo.build({ id: 1, bar: 'xyz' });foo.isNewRecord = false;//使保存使用 UPDATE 而不是 INSERT INTOfoo.save();

这对我的用例来说是完美的,但我想知道我是否在续集中破坏了任何东西.

解决方案

build 函数中有一个参数,它接受一个名为 options 的对象.options 有一个属性 isNewRecord 默认为 true.如果您将此设置为 false 并使用 update(),它将在您设置主键后更新现有记录.

let instance = await db.Model.build({}, {isNewRecord: false});const 结果 = 等待 instance.update({id:instanceId,列:新值});

来源p>

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.

解决方案

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

这篇关于Sequelize:使用 build 更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆