I'm trying to figure out how N:M works in sequelize, and I have a problem with populating the "through" table.
So I have these models :
Product / Category models
'use strict';
module.exports = (sequelize, DataTypes) => {
const Category = sequelize.define('Category', {
name: DataTypes.STRING
}, {});
return Category;
};
module.exports = (sequelize, DataTypes) => {
const Product = sequelize.define(
'Product',
{
name: DataTypes.STRING,
price: DataTypes.INTEGER,
description: DataTypes.TEXT,
inStock: DataTypes.BOOLEAN
},
{}
)
Product.associate = function(models) {
// associations can be defined here
models.Product.belongsToMany(models.Category, {
through: 'Product_categories'
})
models.Category.belongsToMany(models.Product, {
through: 'Product_categories'
})
}
return Product
}
This creates the "Product_categories" table in my database with a categoryId and the productId. Let's say I have a game as a product, which belongs in multiple categories ( lets say ps4 and xbox ).
How do I actually populate the "Product_categories" table and associate the product (game) to categories with Id 1 and 2 ( playstation and xbox ).
I'm still figuring out Sequelize and ORM in general, so this is where I got a little stuck. Am I supposed to add something in the actual model ? Or do I handle it in the route upon product creation ? I'm so confused ><
I read all the documentation, but to be honest I just got a little confused, so I was hoping someone can explain this to me.
Also, this is the route I use to create the said product :
router.post('/product', async (req, res, next) => {
try {
const { name, price, description, inStock } = req.body
const createdProduct = await Product.create({
name,
price,
description,
inStock
})
res.send(createdProduct)
} catch (error) {
next(error)
}
})
Help much appreciated ! Thanks !!
You can try:
await createdProduct.addCategory(category)
or
await createdProduct.addCategorys(categories)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.