Sequelize doesn't create foreign keys as constraints

We are trying to automatically create tables inside PostgreSQL using Sequelize. Unfortunately, it doesn't create foreign keys as constraints. Here's an example of one of my models:

module.exports = function(schema, DataTypes) {

    var definition = {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        deal_id: {
            type: DataTypes.INTEGER
        },
        image: DataTypes.STRING,
    };


    var image = schema.define('Image', definition, {
        tableName: 'images', // this will define the table name
        timestamps: false, // this will deactivate the timestamp columns
        syncOnAssociation: true,

        classMethods: {
            getDefinition: function() {
                return definition;
            },
            associate: function(_models) {
                image.belongsTo(_models.Product, {
                    foreignKey: 'deal_id'
                });
            }
        }
    });

    return image;
};

      

Am I doing something wrong?

0


source to share


1 answer


First, it's not uncommon for an ORM to handle this kind of thing internally, rather than using foreign key constraints in the database.

Second, it's not uncommon for an ORM to require a pair of association statements to initiate all the internal processing that you might expect.

var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
  , User = this.sequelize.define('User', { username: Sequelize.STRING })

User.hasMany(Task)
Task.belongsTo(User)

      

Finally, Sequelize will actually write foreign key declarations to the database, but only if you also declare some action (or inaction) with onUpdate

or onDelete

.



To add link constraints to columns, you can pass onUpdate and onDelete parameters to association calls ...

User.hasMany(Task, { onDelete: 'SET NULL', onUpdate: 'CASCADE' })

CREATE TABLE IF NOT EXISTS `Task` (
  `id` INTEGER PRIMARY KEY, 
  `title` VARCHAR(255), 
  `user_id` INTEGER REFERENCES `User` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
);

      

Code example source

+4


source







All Articles