I am trying to learn sequelize, but am having trouble getting a n:m object created. So far I have my 2 models that create 3 tables (Store, Product, StoreProducts) and the models below:
models/Store.js
module.exports = (sequelize, DataTypes) => {
return Store = sequelize.define('Store', {
name: {
type: DataTypes.STRING,
},
address: {
type: DataTypes.STRING,
}
});
};
models/Product.js
module.exports = function(sequelize, DataTypes) {
return Product = sequelize.define('Product', {
name: {
type: DataTypes.STRING,
}
});
};
models/Index.js
models.Store.belongsToMany(models.Products, {through: 'StoreProducts', foreignKey: 'storeId'});
models.Products.belongsToMany(models.Store, {through: 'StoreProducts', foreignKey: 'productId'});
I want to "add" the following json object.
var store = {
name:'corner store',
address: '123 Main Street',
products: [
'string beans', 'coffee', 'milk'
]
};
Looking for any direction, I've tried about 10 routes and the best I was able to get was the Store and Product records created, but nothing relational.
Have a look at nested creation (the feature is not documented yet)
This will create both stores and products and associate the two.
Note, that this only works for creation - you cannot use it to associate new products with an already existing store etc.