I'm trying to create a parent/child relationship in Sequelize and am getting odd results when attempting to insert. I have a Scope
model, which is the parent, and Component
which is the child. I setup the relationships between them like this:
models.Scope.hasMany(models.Component)
models.Component.belongsTo(models.Scope)
My create method for Component looks like this:
const component = this.Component.build({name})
component.setScope(scope)
return component.save({transaction})
When I go to test the relationship with the following code:
elementRepository.createScope('Parent', transaction).then((scope) => {
elementRepository.createComponent('Child', scope, transaction).then(component => {
done()
})
})
I see that it inserts the two records correctly, but then, for some reason after the transaction rolls back, it attempts to insert a record into Component
again, but only with the relationship:
Executing (080e8b1d-8f01-4d35-af8c-0e0bf0e4c600): START TRANSACTION;
Executing (080e8b1d-8f01-4d35-af8c-0e0bf0e4c600): SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Executing (080e8b1d-8f01-4d35-af8c-0e0bf0e4c600): SET autocommit = 0;
Executing (080e8b1d-8f01-4d35-af8c-0e0bf0e4c600): INSERT INTO `Scopes` (`id`,`name`) VALUES (DEFAULT,'Parent');
Executing (080e8b1d-8f01-4d35-af8c-0e0bf0e4c600): INSERT INTO `Components` (`id`,`name`,`scope_id`) VALUES (DEFAULT,'Child',9);
✓ should create a scope, component, and element
Executing (080e8b1d-8f01-4d35-af8c-0e0bf0e4c600): ROLLBACK;
Executing (default): INSERT INTO `Components` (`scope_id`) VALUES (9);
The documentation isn't very clear on how this should be handled, and the fact that the error only occurs after the transaction has rolled back seems very odd to me.
via Spencer Uresk
No comments:
Post a Comment