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

106
Views
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
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!