I have three entities: User, Products, UserProduct
const User = dbConnection.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
}
}, { tableName: 'users', timestamps: false });
User.belongsToMany(Product, { as: 'products', through: { model: UserProduct }, foreignKey: 'userId', otherKey: 'productId' })
const Product = dbConnection.define('product', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
}
}, { tableName: 'products', timestamps: false });
const UserProduct = dbConnection.define('user_product', {
userId: {
type: Sequelize.INTEGER
},
productId: {
type: Sequelize.INTEGER
}
}, { tableName: 'user_product', timestamps: false });
If I run current code sequelize will create row in user table, product table and in user_product table.
const create = async (user) => {
return User.create(user, {
include: [{ model: Product, as: 'products' }]
});
};
await create({ name: 'Vlad', products: [{ name: '12' }] })
How to write code to create row in user table and user_product if PRODUCT already exists. (I don`t neet to create product, only to assosiate them)