在 MySQL 中使用 sequelize 自动增加 id [英] Auto increment id with sequelize in MySQL
问题描述
我在 NodeJS 中有以下模型,带有 sequelize 和 MySQL 数据库:
I have the following model in NodeJS with sequelize and a MySQL database:
var Sequelize = require('sequelize');
var User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
...
};
我正在尝试使用以下代码将新用户添加到我的数据库中:
I am trying to add a new user to my databse with the below code:
sequelize.transaction().then(function(t) {
User.create({/* User data without id */}, {
transaction: t
}).then(function() {
t.commit();
}).catch(function(error) {
t.rollback();
});
});
在那之后,我收到下一个错误:
After that, I am getting the next error:
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): START TRANSACTION;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): SET autocommit = 1;
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): INSERT INTO `user` (`id`, /* next fields */) VALUES (DEFAULT, /* next values */);
Executing (47f19f7b-a02d-4d72-ba7e-d5045520fffb): ROLLBACK;
和错误信息:
[SequelizeDatabaseError: ER_NO_DEFAULT_FOR_FIELD: Field 'id' doesn't have a default value]
name: 'SequelizeDatabaseError',
message: 'ER_NO_DEFAULT_FOR_FIELD: Field \'id\' doesn\'t have a default value'
但是,如果我手动设置 id 值,它就可以工作.似乎 sequelize 试图在 id 字段中设置一个默认值,而不是设置一个自动增量整数.我也在我的数据库中将此字段定义为 autoIncrement.
However, if I manually set the id value, it works. It seems sequelize is trying to set a default value in the id field, instead setting an autoincrement integer. I have defined this field as autoIncrement in my database too.
我怎么能做这个插入?我必须手动设置 id 吗?
How could I do this insertion? Do I have to set the id manually?
编辑
这是我的表定义:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` varchar(9) NOT NULL,
`name` varchar(20) NOT NULL,
`email` varchar(30) DEFAULT NULL,
`birthdate` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uid_UNIQUE` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
推荐答案
你必须确保你根本没有发送 id
键.
You must be sure you're not even sending the id
key at all.
我做了一个快速的最小测试,它似乎工作得很好:
I have done a quick minimal test and it seemed to work great:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('cake3', 'root', 'root', {
define: {
timestamps: false
},
});
var User = sequelize.define('user1', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: Sequelize.STRING
}
});
sequelize.transaction().then(function(t) {
User.create({name:'test'}, {
transaction: t
}).then(function() {
t.commit();
}).catch(function(error) {
console.log(error);
t.rollback();
});
});
表转储:
CREATE TABLE `user1s` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
ALTER TABLE `user1s`
ADD PRIMARY KEY (`id`);
ALTER TABLE `user1s`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;
这篇关于在 MySQL 中使用 sequelize 自动增加 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!