无法更新的 Sequelize 列

2021-11-15 00:00:00 api rest node.js mysql sequelize.js

是否可以使用 Sequelize 在 MySQL 表上创建一个列,该列在创建新行时可以初始化,但永远不会更新?

Is it possible to create a column on a MySQL table using Sequelize that can be initialized when creating a new row, but never updated?

例如,REST 服务允许用户更新其个人资料.他可以更改除id 以外的任何字段.我可以从 API 路由上的请求中去除 id ,但这有点多余,因为有许多不同的模型表现相似.理想情况下,我希望能够在 Sequelize 中定义一个约束,以防止将 id 列设置为 DEFAULT 以外的任何内容.

For example, a REST service allows a user to update his profile. He can change any field except his id. I can strip the id from the request on the API route, but that's a little redundant because there are a number of different models that behave similarly. Ideally, I'd like to be able to define a constraint in Sequelize that prevents the id column from being set to anything other than DEFAULT.

目前,我正在使用 setterMethod 作为 id 来手动抛出 ValidationError,但这似乎是 hackish,所以我想知道如果有更干净的方法来做到这一点.更糟糕的是,这个实现仍然允许在创建新记录时设置 id,但我不知道如何解决这个问题,因为当 Sequelize 生成它调用 setterMethods.id 的查询时 将值设置为 DEFAULT.

Currently, I'm using a setterMethod for the id to manually throw a ValidationError, but this seems hackish, so I was wondering if there's a cleaner way of doing this. Even worse is that this implementation still allows the id to be set when creating a new record, but I don't know a way around this as when Sequelize generates the query it calls setterMethods.id to set the value to DEFAULT.

return sequelize.define('Foo',
    {
        title: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true,
            validate: {
                notEmpty: true
            }
        }
    },
    {
        setterMethods: {
            id: function (value) {
                if (!this.isNewRecord) {
                    throw new sequelize.ValidationError(null, [
                        new sequelize.ValidationErrorItem('readonly', 'id may not be set', 'id', value)
                    ]);
                }
            }
        }
    }
);

推荐答案

看看这个 Sequelize 插件:

Look at this Sequelize plugin:

https://www.npmjs.com/package/sequelize-noupdate-attributes

它增加了对 Sequelize 模型中无更新和只读属性的支持.

It adds support for no update and read-only attributes in Sequelize models.

在您的特定情况下,您可以使用以下标志配置属性:

In your specific case, you could configure the attribute with the following flags:

{
  title: {
    type: DataTypes.STRING,
    allowNull: false,
    unique   : true,
    noUpdate : true
  }
}

这将允许 title 属性的初始设置为空,然后一旦设置就阻止任何进一步的修改.

That will allow the initial set of the title attribute if is null, and then prevent any further modifications once is already set.

免责声明:我是插件作者.

相关文章