Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda