0

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'})
 };

1 Answer 1

2

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;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.