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

112
Vistas
Sequelize many-to-many relation with repeated foreign keys

Suppose I have the following tables:

Messages:
+----+----------------------------------------------------------------+
| id |                            content                             |
+----+----------------------------------------------------------------+
|  1 | Please call 111-111-1111. I repeat: CAN YOU CALL 111-111-1111? |
|  2 | My number is 111-111-1111.                                     |
|  3 | Please call me at either 222-222-2222 or 333-333-3333          |
+----+----------------------------------------------------------------+
PhoneNumbers:
+----+--------------+------------------+
| id |    number    |     provider     |
+----+--------------+------------------+
|  1 | 111-111-1111 | AT&T             |
|  2 | 222-222-2222 | Deutsche Telekom |
|  3 | 333-333-3333 | Verizon          |
+----+--------------+------------------+

Now I would like to create a table that represent each occurrence of a phone number in a message:

PhoneNumberOccurrences:
+----+-----------+---------------+
| id | MessageId | PhoneNumberId |
+----+-----------+---------------+
|  1 |         1 |             1 |
|  2 |         1 |             1 |
|  3 |         2 |             1 |
|  4 |         3 |             2 |
|  5 |         3 |             3 |
+----+-----------+---------------+

Here is the code to define this table:

const Occurence = sequelize.define("PhoneNumberOcurrence", {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
  },
});
PhoneNumber.belongsToMany(Message, { through: Occurence });
Message.belongsToMany(PhoneNumber, { through: Occurence });

However if I try to fill the first two rows of the table:

const message = await Message.findOne({ where: { id: 1 } });
const number = await PhoneNumber.findOne({ where: { id: 1 } });
await message.addPhoneNumber(number);
await message.addPhoneNumber(number);

The first row gets inserted successfully but the second row did not. My guess is because of the repeating foreign keys. How can I insert even if the foreign keys are repeated?

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