DEV Community

loading...

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

loizenai
Software Engineer - Founder at https://loizenai.com
・1 min read

https://grokonez.com/node-js/sequelize-one-to-many-association-nodejs-express-mysql

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', {/* ... */})

Company.hasMany(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', {
    /*attributes*/
    
    return Product;
}

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

https://grokonez.com/node-js/sequelize-one-to-many-association-nodejs-express-mysql

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

Discussion (0)

Forem Open with the Forem app