Farrukh Azeem
Farrukh Azeem

Reputation: 1

How to define foreign key constraint in postgres using sequelize ORM?

I am trying to create one to many foreign key constraint between two tables. A client can have many environments.

Here is my snippet in the model.

Client.associate = function(models) {
   Client.hasMany(models.Enviornment, {as: 'enviornments', foreignKey: 'clientId'})
 };

Upvotes: 0

Views: 2582

Answers (1)

zshan4444
zshan4444

Reputation: 430

The solution is here.

The client has many environments. (one to many association )

Here is a code snippet for a model client.

module.exports = (sequelize, DataTypes) => {

let client = sequelize.define ('client', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, field: 'id' },
   ...
    }, {

    associate: models => {
        client.hasMany (models.enviornment, {
            foreignKey: { name: 'client_id', allowNull: false }
        });
    },

});
return client;
};

Here is a code snippet for a model enviornment.

module.exports = (sequelize, DataTypes) => {

let enviornment = sequelize.define ('enviornment', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, field: 'id' },
   ...
    }, {

    associate: models => {
        enviornment.belongsTo (models.client, {
            foreignKey: { name: 'client_id', allowNull: false }
        });
    },

});
 return enviornment;
};

Upvotes: 2

Related Questions