Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sequelize Postgres Migration update constraint helper for changing the value of onUpdate and onDelete.
const constraintOpts = {
onDelete: 'NO ACTION',
onUpdate: 'NO ACTION'
* updateConstraint
* @param {QueryInterface} queryInterface - sequelize queryInterface proviced in up/down methods of migrations
* @param {SequelizeModel} model - base sequelize model where the foreign key exists
* @param {String} fkey - foreign key field name (ex: userId)
* @param {SequelizeModel} referenced - The sequelize model that the foreign key references
* @param {Object} options - The onDelete/onUpdate values. defaults: NO ACTION. Accepts: 'CASCADE', "SET NULL", etc
export function updateConstaint(queryInterface, model, fkey, referenced, options = constraintOpts) {
const constraint = `"${model.getTableName()}_${fkey}_fkey"`;
return queryInterface.sequelize.query(`
ALTER TABLE "${model.getTableName()}"
DROP CONSTRAINT ${constraint},
ADD CONSTRAINT ${constraint}
FOREIGN KEY ("${fkey}")
REFERENCES "${referenced.getTableName()}"(id)
ON UPDATE ${options.onUpdate} ON DELETE ${options.onDelete};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment