I know this can be possible by using a raw query like the one used in this question to remove a constraint, however, is there any built-in method to drop foreign keys from Sequelize.js?
Not for now - https://github.com/sequelize/sequelize/issues/5212
In our team we use this approach, methods from QueryGenerator
add a trick for you
let dropFKSQL = queryInterface.QueryGenerator.dropForeignKeyQuery("tableName", "foreignKey")
return queryInterface.sequelize.query(dropForeignKeySQL);
But the difference in auto generated foreign keys with postfix _ibfk_{index}
(by MySQL itself) and _idx
(by sequelize) are a huge pain in the ass. You can use this method to get FK dynamically:
public getForeignKeyName(tableName: string, columnName: string, opts: { queryInterface: QueryInterface }): Promise<string> {
let sqlz = opts.queryInterface.sequelize;
let sql = `
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = '${dbSchema}'
AND TABLE_NAME = '${tableName}'
AND COLUMN_NAME = '${columnName}'
`;
return sqlz.query(sql, { type: sqlz.QueryTypes.SELECT })
.then((result: { CONSTRAINT_NAME: string }[]) => {
if (!result || !result[0] || !result[0].CONSTRAINT_NAME) {
return null;
}
return result[0].CONSTRAINT_NAME;
});
}
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