OhLongJohnJohnson
OhLongJohnJohnson

Reputation: 181

How to obtain inheritance in sequelize models

I am running a Node.js service with sequelize. I have 4 different types of users, all share some of the same attributes like name, password etc. and all have user-role specific attributes.

Currently, I have all 4 models defined as separate models. This gives code duplication and multiple calls to the database if I want to retrieve all users.

How can I obtain a form of inheritance with sequelize? I would like to achieve something like this:

ER DB diagram

Upvotes: 7

Views: 6045

Answers (1)

mohdule
mohdule

Reputation: 538

In order to achieve your ERD above, you can simply Associate each Role model Instructor, Student, Administrator, Janitor to the main User model using the Sequelize Associations, it's very flexible to define foreignKeys, targetKeys and sourceKey, take a look at the Association part of Sequelize documentation over here.

I'm not really sure what specific entities relationship type this would be (meaning belongsTo, belongsToMany, ..etc) but according to your diagram it is a hasOne relationship.

Upvotes: 5

Related Questions