Naming strategy

By default sequelize will use the model name (the name passed to sequelize.define) to figure out the name of the model when used in associations. For example, a model named user will add the functions get/set/add User to instances of the associated model, and a property named .user in eager loading, while a model named User will add the same functions, but a property named .User (notice the upper case U) in eager loading.

As we've already seen, you can alias models in associations using as. In single associations (has one and belongs to), the alias should be singular, while for many associations (has many) it should be plural. Sequelize then uses the inflection library to convert the alias to its singular form. However, this might not always work for irregular or non-english words. In this case, you can provide both the plural and the singular form of the alias:

  1. User.belongsToMany(Project, { as: { singular: 'task', plural: 'tasks' }})
  2. // Notice that inflection has no problem singularizing tasks, this is just for illustrative purposes.

If you know that a model will always use the same alias in associations, you can provide it when creating the model

  1. class Project extends Model {}
  2. Project.init(attributes, {
  3. name: {
  4. singular: 'task',
  5. plural: 'tasks',
  6. },
  7. sequelize,
  8. modelName: 'project'
  9. })
  10. User.belongsToMany(Project);

This will add the functions add/set/get Tasks to user instances.

Remember, that using as to change the name of the association will also change the name of the foreign key. When using as, it is safest to also specify the foreign key.

  1. Invoice.belongsTo(Subscription)
  2. Subscription.hasMany(Invoice)

Without as, this adds subscriptionId as expected. However, if you were to say Invoice.belongsTo(Subscription, { as: 'TheSubscription' }), you will have both subscriptionId and theSubscriptionId, because sequelize is not smart enough to figure that the calls are two sides of the same relation. 'foreignKey' fixes this problem;

  1. Invoice.belongsTo(Subscription, { as: 'TheSubscription', foreignKey: 'subscription_id' })
  2. Subscription.hasMany(Invoice, { foreignKey: 'subscription_id' })