Search code examples
node.jssequelize.jsnode-sqlite3

How to create associations between models in sequelize


I am creating a game using node.js and I would like to save data in a database (sqlite3) using sequelize.js.

I have 2 models right now: User and Clan.

I want them to have such relationships:

  • A User can have a Clan as clan
  • A Clan can have a User as owner
  • A Clan can have many User as members, owner included

In other words, <User>.clan should be an instance of a Clan, <Clan>.owner should be an instance of a User, and <Clan>.members should be an array of User instances.

Currently while trying to setup such relationships, I get cyclic dependency errors.


Solution

  • Based on Sequelize documentation, you should use constraints: false on your models declaration (only on Clan -> Owner relationship in your case) to avoid cyclic dependency errors.