Issues with Many-to-Many Relationships in CakePHP 4: Existing Tags Not Replaced, Only Appended

Hello everyone,

I’m currently working on a project using CakePHP 4 and have set up a one-to-many relationship between two tables: Pages and Tags. In my form for Pages, I can select existing tags using the form field Tags._ids, and adding new tags works perfectly fine.

However, I’m facing an issue: When I try to select different tags for a post, CakePHP 4 doesn’t delete the old tags on the existing relation but rather keeps appending more tags, resulting in an accumulation of tags on the page instead of replacing the existing ones.

Why does CakePHP behave this way, and how can I change this behavior so that when selecting new tags, the existing relation is deleted and replaced with the new tags?

I would greatly appreciate your help and possibly examples on how to manually control this behavior to achieve the desired functionality.

Thank you in advance!

Is the saveStrategy in your association append or replace?

Thanks Zuluru :slight_smile: that was the right tip. I also changed it to replace. Was confused in the documentation. I thought that the replace strategy would be default.

There doesn’t happen to be an event that fires after the relationship is deleted, right? At least I didn’t find anything. Would be very practical to clean the entity. E.g. Convert field entries back to default after deleting the relationship. I’m currently implementing it in the controller after the save statement, which uses the cloned entity and the entity to change and change the corresponding relation chips after saving.