Creating Associations with Sequelize

Posted on by By Gagan Manda, in Databases | 0

In this blog, we will create the Models with associations and this is a continuation to the previous blog “Creating models with sequelize”. The setup process is explained in the previous blog Creating Associations is nothing but mapping the models with their foreign keys.

First let us create two models Employee and Address where Employee will have columns as ‘id’, ‘Employee_name’ and Address model will have ‘id’, ‘town’ where id in Employee is a foreign key to id in Address model.

Create a file named Employee.js in /models and add the following code.

'use strict';
module.exports = (sequelize, DataTypes) => {
var Employee = sequelize.define(‘Employee’, {
id: {
type: DataTypes.STRING,
primaryKey : true
},
Employee_name: {
type : DataTypes.STRING,
allowNull : false,
},

},
{
tableName: ‘Employee’
}
);

return Employee;
};

Create another file named Address.js and add the following code

module.exports = (sequelize, DataTypes) => {
var Address= sequelize.define(‘Address, {
id: {
type: DataTypes.STRING,
References : {
model : Employee, 
key : ‘id’
},
onDelete : ‘CASCADE’
},
town: {
type : DataTypes.STRING,
allowNull : false,
},

},
{
tableName: ‘Address’
}
);

return Address;
};

In the above code for Id column we are adding references in which model is the model name in which our foreign key is present and id is the column name of a foreign key.

We are using onDelete as cascade because when we are trying to delete a record from Address model it will throw an error because corresponding employee details are still present in the employee model. So, when we use cascade onDelete this will delete the corresponding record in the employee table and in the Address table.

For any queries please get back to us at support@helicaltech.com

Thanks,
Gagan
BI Developer
Helical IT Solutions Pvt Ltd

logo

Best Open Source Business Intelligence Software Helical Insight Here

logo

A Business Intelligence Framework


logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments