Skip to content

Instantly share code, notes, and snippets.

@lucasscariot
Last active June 22, 2023 17:08
Show Gist options
  • Star 48 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save lucasscariot/5b8747fbc8a6948a805c646fae4ceef8 to your computer and use it in GitHub Desktop.
Save lucasscariot/5b8747fbc8a6948a805c646fae4ceef8 to your computer and use it in GitHub Desktop.
Composite Primary Key in Sequelize
/*
* Migration
*/
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Users', {
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})
.then(() => {
return queryInterface.sequelize.query('ALTER TABLE "Users" ADD CONSTRAINT "username" PRIMARY KEY ("firstName", "lastName")');
})
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Users');
}
};
/*
* Model
*/
'use strict';
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('users', {
firstName: {
type: DataTypes.STRING,
primaryKey: true,
},
lastName: {
type: DataTypes.STRING,
primaryKey: true,
},
email: DataTypes.STRING
});
User.removeAttribute('id');
return User;
};
@acanimal
Copy link

This gist save me the day !!! I just modified the create compound primary sentence to use queryInterface.addConstraint instead a raw query.
Thanks !!!

@jmlsf
Copy link

jmlsf commented Mar 2, 2018

Hey just came across this gist and it really helped me. After some digging, I just wanted to point out that you could also add the constraint like this if you want to avoid the raw sql:

queryInterface.addConstraint('Users', ['firstName', 'lastName'], {
      type: 'primary key',
      name: 'users_pkey'
    });

@tomprogers
Copy link

You can also just say primaryKey:true on several columns, and sequelize will understand that it's a composite key. At least, it does on top of postgres.

(Against sequelize@4.33.4)

@narayana1043
Copy link

How do we use findOne() method in this case? I want to find a record given the first name and the last name using findOne() method which looks up the row using the primary key

@Valindo
Copy link

Valindo commented May 7, 2019

@narayana1043
You've still got to use the where clause in findOne()
Something like this findOne({where:{composite_key_1:value})

Let me know if this was helpful, Thanks.

@BartusZak
Copy link

I did like @jmlsf mentioned, but had to add 'SET FOREIGN_KEY_CHECKS = 0'

ERROR: Cannot change column 'itemId': used in a foreign key constraint 'table_itemId_foreign_idx'

.then(() => queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 0'))
      .then(() =>
        queryInterface.addConstraint(
          'table',
          ['itemId', 'item2Id'],
          {
            type: 'primary key',
            name: 'name_ibfk_1'
          }
        )
      )
      .then(() => queryInterface.sequelize.query('SET FOREIGN_KEY_CHECKS = 1')),

@L-U-C-K-Y
Copy link

L-U-C-K-Y commented Apr 14, 2020

@narayana1043
You've still got to use the where clause in findOne()
Something like this findOne({where:{composite_key_1:value})

Let me know if this was helpful, Thanks.

When I create a composite key, by specifying primaryKey: true multiple times, am I able to find out the name of the composite key to use in the where clause?

Thanks

@yoya93
Copy link

yoya93 commented Dec 10, 2020

@ narayana1043
Todavía tienes que usar la wherecláusula en findOne()
algo como estofindOne({where:{composite_key_1:value})
Hágame saber si esto fue útil, gracias.

Cuando creo una clave compuesta, al especificar primaryKey: truevarias veces, ¿puedo averiguar el nombre de la clave compuesta para usar en la cláusula where?

Gracias

Hi!!! You could know how to get the name thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment