One-To-Many associations (hasMany)

One-To-Many associations are connecting one source with multiple targets. The targets however are again connected to exactly one specific source.

  1. class User extends Model {}
  2. User.init({/* ... */}, { sequelize, modelName: 'user' })
  3. class Project extends Model {}
  4. Project.init({/* ... */}, { sequelize, modelName: 'project' })
  5. // OK. Now things get more complicated (not really visible to the user :)).
  6. // First let's define a hasMany association
  7. Project.hasMany(User, {as: 'Workers'})

This will add the attribute projectId to User. Depending on your setting for underscored the column in the table will either be called projectId or project_id. Instances of Project will get the accessors getWorkers and setWorkers.

Sometimes you may need to associate records on different columns, you may use sourceKey option:

  1. class City extends Model {}
  2. City.init({ countryCode: Sequelize.STRING }, { sequelize, modelName: 'city' });
  3. class Country extends Model {}
  4. Country.init({ isoCode: Sequelize.STRING }, { sequelize, modelName: 'country' });
  5. // Here we can connect countries and cities base on country code
  6. Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'});
  7. City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'});

So far we dealt with a one-way association. But we want more! Let's define it the other way around by creating a many to many association in the next section.