Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set primary key type to UUID via Sequelize CLI

I'm creating a DB model via Sequelize CLI with this command:

sequelize model:create --name User --attributes "firstname:string, lastname:string" 

This creates the corresponding migration script:

'use strict'; module.exports = {   up: function(queryInterface, Sequelize) {     return queryInterface.createTable('Users', {       id: {         allowNull: false,         autoIncrement: true,         primaryKey: true,         type: Sequelize.INTEGER       },       firstname: {         type: Sequelize.STRING       },       lastname: {         type: Sequelize.STRING       },       createdAt: {         allowNull: false,         type: Sequelize.DATE       },       updatedAt: {         allowNull: false,         type: Sequelize.DATE       }     });   },   down: function(queryInterface, Sequelize) {     return queryInterface.dropTable('Users');   } }; 

As shown, the primary key is set to integer.

Is there a way to default the CLI to use UUID instead?

like image 707
rtorres Avatar asked Nov 22 '16 05:11

rtorres


People also ask

How do you set a primaryKey in Sequelize?

The primaryKey option allows you to assign the PRIMARY KEY constraint to your model columns. Consider the following Sequelize model example: const User = sequelize. define("User", { user_id : { type: Sequelize.

How do I change the column type in Sequelize?

To Fix Sequelize js , how do we change column type in migration, you can use changeColumn instead of addColumn because addColumn will add new column in your table . you can define your migration like this : Migration File module. exports = { up: (queryInterface, Sequelize) => { return Promise. all([ queryInterface.

How do you create a composite primaryKey in Sequelize?

You can create composite primary keys in Sequelize by specifying primaryKey: true against more than one column. E.g. how can we associate a table to this composite key.


1 Answers

You can simple use the type UUIDV4 that comes with Sequelize. Here is more details : UUIDV4

For example making this definition:

id: {   type: Sequelize.UUID,   defaultValue: Sequelize.UUIDV4,   allowNull: false,   primaryKey: true } 

This is not using the Sequelize CLI but you can use that native UUIDV4 by manually changing that.

like image 181
Ismael Terreno Avatar answered Sep 18 '22 01:09

Ismael Terreno