Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Sequelize create row incude many to many relation

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)

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!