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-One association – NodeJS/Express, MySQL
- Sequelize Many-to-Many association – NodeJS/Express, MySQL
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
Top comments (0)