我有续集模型:
'use strict';
module.exports = (sequelize, DataTypes) => {
const Image = sequelize.define('Image', {
id: {
type: DataTypes.BIGINT,
autoIncrement: true,
unique: true,
primaryKey: true
},
url: {
type: DataTypes.STRING,
allowNull: false,
}
},
{
timestamps: false
});
Image.associate = (models) => {
//some association here
};
return Image;
};
我正在尝试创建一个新记录,如下所示:
const img = await Images.create({
url: '/newUrl'
}).catch(error => {
throw errors.initError(error);
});
它执行查询
执行中(默认):插入“图像”(“ id”,“ url”)值 (默认,'/ newUrl')返回*;
我收到一个错误
{
"message": "id must be unique",
"type": "unique violation",
"path": "id",
"value": "18",
"origin": "DB",
"instance": {
"id": null,
"url": "/newUrl"
},
"validatorKey": "not_unique",
"validatorName": null,
"validatorArgs": []
}
是否应该自己单独处理自动递增字段?
答案 0 :(得分:2)
当您在提供id
的数据库中手动创建条目时,会发生这种情况。
为了证明这一点,您可以尝试将它们用于postgres
create table users (id serial NOT NULL PRIMARY KEY, name varchar(40));
insert into users (name) values ('abhinavd');
select * from users;
insert into users (id, name) values (2, 'abhinavd');
insert into users (name) values ('abhinavd');
最后一个插入将抱怨id
必须唯一