After some research I don't seem to be able to find a great approach doing following:
I wan't to add a new column, to an existing table, that should be an auto incrementing integer, starting with the value of 1000.
My migration file is for now simple and obvious:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return Promise.all([
queryInterface.addColumn(
'Orders',
'orderRef',
{
autoIncrement: true,
type: Sequelize.INTEGER
}
)
])
},
down: {...
}
};
So this adds the column to the table unproblematic. But I don't seem to be able to find a great approach to set the value to start at 1000 and increment from there.
I know I could run a query like ALTER TABLE Orders AUTO_INCREMENT = 1000;
but I would very much appreciate to keep it in Sequelize.
I'm using a PostgreSQL database and Sequelize version 4.38.1.
Does anyone know a nice way around this issue?
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
Sequelize will assume your table has a id primary key property by default.
There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.
It is already present in Sequelize. There is an option called initialAutoIncrement. This sets the initial AUTO_INCREMENT value for the table in MySQL.
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
'User',
{
id: {
type: DataTypes.BIGINT(20),
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING(500),
allowNull: false,
},
},
{
initialAutoIncrement: 1000,
}
);
return User;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With