Prevent saving dupplicated on belongToMany association

I have tables Parents and CourseTypes,

When every parent interested in a course type, they submit their profile with course type ID, then in my application, Parents Table will call link() to save belongToMany association between them.

However, if you user click on interest button again, another link is created between 2 entities, which is identical to previous link.

I have tried to use Application Rules, check for uniqueness of parent_id and course_type_id on join table, but then link() will has runtime error like below:

Cannot commit transaction - rollback() has been already called in the nested transaction

I then tried to set the association with saveStrategy to ‘replace’ , on both side of associations, but dupplications still appear in database.

Please kindly point me a direction to go.

Thanks very much.

Can you share the implementation of the rule that you tried?

This is Rules definition, the commented line is the one that cause runtime error
class CourseTypesParentsTable extends Table

public function buildRules(RulesChecker $rules): RulesChecker
    $rules->add($rules->existsIn(['ics_parent_id'], 'IcsParents'));
    $rules->add($rules->existsIn(['course_type_id'], 'CourseTypes'));
    //$rules->add($rules->isUnique(['ics_parent_id', 'course_type_id']));

    return $rules;

According to the book, that does seem like it should work. The rollback error doesn’t seem like it would come from this, but rather maybe some event handler?

I did not implement any event handler yet. Not that far.

Is there any suggestion for me to troubleshoot, Zuluru ?

Thank you very much.

If you’ve got xdebug or something like it set up, you could put a breakpoint in the rollback function in Cake, and see where that’s being triggered from. Without xdebug, you can sort of do the same with a trigger_warning call in there, or something similar to show you the call stack.

CakePHP isn’t magic, it’s just PHP code, which you can debug the same as any other PHP code.