I have two tables: User
and Scope
; with the cardinality of N (User
) -> M (Scope
). When I insert fake records inside the User
and the Scope
tables, everything goes well, but if I insert fake records (ids from the User
and Scope
tables) inside the UserScope
relation table, which represents the relation between User
and Scope
, I receive the errors:
1:
Unhandled rejection SequelizeUniqueConstraintError: Validation error
2:
Unhandled rejection SequelizeForeignKeyConstraintError: Cannot add or update a child row: a foreign key constraint fails (`graph`.`userScope`, CONSTRAINT 'userScope_ibfk_1' FOREIGN KEY (`scopeId`) REFERENCES `scope` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
I had tried to debug via MySQL console (SHOW ENGINE INNODB STATUS\G
):
CONSTRAINT 'userScope_ibfk_1' FOREIGN KEY ('scopeId') REFERENCES 'scope' ('id') ON DELETE CASCADE ON UPDATE CASCADE
Trying to add in child table, in index userScope_userId_scopeId_unique tuple:
DATA TUPLE: 3 fields;
0: len 4; hex 80000008; asc ;;
1: len 4; hex 8000000a; asc ;;
2: len 4; hex 80000001; asc ;;
But in parent table 'graph'. 'scope', in index PRIMARY,
the closest match we can find is record:
PHYSICAL RECORD: n_fields 1; compact format; info bits 0
0: len 8; hex 696e66696d756d00; asc infimum ;;
And I had found this question that makes me think that the way I'm inserting data in the relation table is not right, i.g, duplicate relations are being added in the relation table.
I'm inserting the relations this way:
import db from "./models";
import faker from "faker";
import times from "lodash.times";
import random from "lodash.random";
const amount = 10;
db.user.bulkCreate(
times(amount, () => ({
email: faker.internet.email(),
password: faker.internet.password(),
name: `${faker.name.firstName} ${faker.name.lastName}`,
birth: Date.now()
}))
)
db.scope.bulkCreate(
times(amount, () => ({
title: faker.hacker.verb()
}))
)
db.userScope.bulkCreate(
times(amount, () => ({
scopeId: random(1, amount),
userId: random(1, amount)
}))
);
The tables:
I expect to insert fake relations in the UserScope
table, without any errors and in a random way.
Obs: I had set the amount
to 1
/ set manually the ids and I still receiving this error. I had also already read threads like this one, this one but...