0

I need a model to have an external_id field, but that id can come from different models.

For example I have a Customers model, and the customer can be either an organization or an invididual. The Organizations and Individuals models are obviously different, and I need to point to to either of those.

My idea would be to have an external_id field in Customers, and then a type field with that would allow me to point the external_id to the proper model.

Is this possible in Sequelize?

How would I define this relationship in Sequelize and query it afterwards?

Pier
  • 10,298
  • 17
  • 67
  • 113
  • Can you put how you have define your models until now? – Ellebkey Jun 07 '17 at 16:18
  • @Ellebkey This is theoretical, I don't have any model definitions – Pier Jun 07 '17 at 18:47
  • Well actually you have two ways to do the associations for this. 1. You can define Customer association with `belongsTo(models.Organization);`. Same with the Individuals. This way you will create two foreign keys for each model. 2. Or, you can `hasMany(models.Organization)`. This way you'll create a foreign key refering the Customer model. [This post](https://stackoverflow.com/questions/12255731/supertype-subtype-database-design) actually explain the SuperType- SubType Models. – Ellebkey Jun 07 '17 at 19:11
  • But what if I want to add more customer types in the future? Adding more fields is not really a scalable solution. – Pier Jun 07 '17 at 19:45
  • Second option is better cuz you add the customer reference on each new model – Ellebkey Jun 07 '17 at 20:24

0 Answers0