gpt4 book ai didi

javascript - 如何使用 sequelize beforeCreate 自动生成 Id 值?

转载 作者:行者123 更新时间:2023-12-03 22:19:28 25 4
gpt4 key购买 nike

我正在尝试生成 BINARY(16) Id 的模型的值。

我使用了 defaultValue 参数,但最终得到了

duplicate key errors in mysql



.

所以我发现如果我使用 beforeCreate 那么它每次都是唯一的但是当我做实际的创建时我得到

Id can not be null errors



我的模型:
const utility = require('utils/utilities');


module.exports = function(sequelize, DataTypes) {
const weddings = sequelize.define(
'weddings', {
Id: {
primaryKey: true,
allowNull: false,
type: 'BINARY(16)',
},
Name: {
type: DataTypes.STRING(150),
allowNull: false,
comment: 'null',
},
HouseId: {
type: DataTypes.INTEGER(11),
allowNull: false,
comment: 'null',
references: {
model: 'house',
key: 'Id',
},
},
WDate: {
type: DataTypes.DATE,
allowNull: false,
comment: 'null',
},
Active: {
type: DataTypes.BOOLEAN,
allowNull: false,
comment: 'null',
},
},

{
hooks: {
beforeCreate() {
const generateValue = Buffer.from(utility.generateUID().replace('-', ''), 'hex');
weddings.Id = generateValue;
}
}
}, {
tableName: 'weddings',
}
);

return weddings;
};

错误:

weddings.Id cannot be null



我错过了什么?

最佳答案

您可以像这样使用实例 Hook :

const utility = require('utils/utilities');


module.exports = function(sequelize, DataTypes) {
const weddings = sequelize.define(
'weddings', {
Id: {
primaryKey: true,
allowNull: false,
type: 'BINARY(16)',
},
Name: {
type: DataTypes.STRING(150),
allowNull: false,
comment: 'null',
},
HouseId: {
type: DataTypes.INTEGER(11),
allowNull: false,
comment: 'null',
references: {
model: 'house',
key: 'Id',
},
},
WDate: {
type: DataTypes.DATE,
allowNull: false,
comment: 'null',
},
Active: {
type: DataTypes.BOOLEAN,
allowNull: false,
comment: 'null',
},
},

{
}, {
tableName: 'weddings',
}
);

weddings.beforeCreate(async (data, options) => {
data.Id = await Buffer.from(utility.generateUID().replace('-', ''), 'hex');

});

return weddings;
};


如果您想为每个单独的记录发出钩子(Hook),以及批量钩子(Hook),您可以传递 individualHooks: true来电。
table.update( req.body, {
where: where,
returning: true,
individualHooks: true
plain: true
})

创造:
  db.weddings.create({
...args,
}),

有关其他信息,您可以在以下位置阅读:
https://sequelize.org/v5/manual/hooks.html

关于javascript - 如何使用 sequelize beforeCreate 自动生成 Id 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62332009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com