无法更新的Sequelize列 [英] A Sequelize column that cannot be updated
问题描述
是否可以使用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
,但这似乎有点黑,所以我想知道是否有更清洁的方法来执行此操作.更糟糕的是,此实现在创建新记录时仍允许设置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
}
}
如果为null,将允许初始设置title
属性,然后在设置完毕后阻止进行任何进一步的修改.
That will allow the initial set of the title
attribute if is null, and then prevent any further modifications once is already set.
免责声明:我是插件作者.
这篇关于无法更新的Sequelize列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!