問題描述
是否可以使用 Sequelize 在 MySQL 表上創(chuàng)建一個列,該列在創(chuàng)建新行時可以初始化,但永遠不會更新?
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 服務(wù)允許用戶更新其個人資料.他可以更改除id
以外的任何字段.我可以從 API 路由上的請求中去除 id
,但這有點多余,因為有許多不同的模型表現(xiàn)相似.理想情況下,我希望能夠在 Sequelize 中定義一個約束,以防止將 id
列設(shè)置為 DEFAULT
以外的任何內(nèi)容.
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,所以我想知道如果有更干凈的方法來做到這一點.更糟糕的是,這個實現(xiàn)仍然允許在創(chuàng)建新記錄時設(shè)置 id
,但我不知道如何解決這個問題,因為當(dāng) Sequelize 生成它調(diào)用 setterMethods.id 的查詢時
將值設(shè)置為 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.
在您的特定情況下,您可以使用以下標(biāo)志配置屬性:
In your specific case, you could configure the attribute with the following flags:
{
title: {
type: DataTypes.STRING,
allowNull: false,
unique : true,
noUpdate : true
}
}
這將允許 title
屬性的初始設(shè)置為空,然后一旦設(shè)置就阻止任何進一步的修改.
That will allow the initial set of the title
attribute if is null, and then prevent any further modifications once is already set.
免責(zé)聲明:我是插件作者.
這篇關(guān)于無法更新的 Sequelize 列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!