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?