Auto increment id with sequelize in MySQL

前端 未结 2 1465
感情败类
感情败类 2020-12-24 12:34

I have the following model in NodeJS with sequelize and a MySQL database:

var Sequelize = require(\'sequelize\');
var User = sequelize.define(\'user\', {             


        
相关标签:
2条回答
  • 2020-12-24 12:35

    In migration, add this line of code:

    await queryInterface.sequelize.query("ALTER TABLE table_name AUTO_INCREMENT = 1000000;");
    
    0 讨论(0)
  • 2020-12-24 12:49

    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();
        });
    });
    

    Table dump:

    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;
    
    0 讨论(0)
提交回复
热议问题