DEV Community


Sequelize One-To-Many association – NodeJS/Express, MySQL

Software Engineer - Founder at
・1 min read

Sequelize One-To-Many association – NodeJS/Express, MySQL

In the post, we got started with Sequelize One-To-One association. Today we’re gonna create Sequelize One-To-Many association models with NodeJS/Express, MySQL.

Related posts:

Sequelize One-To-Many

One-To-Many associations are connecting one source with multiple targets. But the targets are connected to only one source.

const Company = sequelize.define('company', {/* ... */})
const Product = sequelize.define('product', {/* ... */})


The above code will add the attribute companyId to Product. Instances of Company has accessors getProducts and setProducts.

We can use sourceKey option to associate records on different columns:

const Company = sequelize.define('company', {
  uuid: {
    type: Sequelize.UUID,
    defaultValue: Sequelize.UUIDV1,
    primaryKey: true
  return Company;

const Product = sequelize.define('product', {
    return Product;

Company.hasMany(Product, {foreignKey: 'fk_companyid', sourceKey: 'uuid'});
Product.belongsTo(Company, {foreignKey: 'fk_companyid', targetKey: 'uuid'});

Sequelize One-To-Many association – NodeJS/Express, MySQL

Discussion (0)

Forem Open with the Forem app