Ensuring uniqueness in Phalcon related n-n models

I have a model contents that has a many to many relationship with tags through the intermediary table contents_tags. When I insert a new row in contents I want to also add multiple tags. While this works fine, I want the tags entries to be unique, so they will be inserted if they are new, or updated (although nothing changes) if they already exist.

This unit test seems to imply that this can be done automatically, but I can't manage to replicate the same behaviour. If I don't have a unique index on my tag table, then I get multiple of the same entries. If I do then the tag model throws an error.

The models for the unit test mentioned above seem to have no special parameters set, and I can't find the actual table declarations for them so I am at a bit of a loss. The models for the unit test can be seen here:

I'm afraid while that does make sure that a value is unique, it will throw a validation error if one of the tags isn't unique. What I want is the behaviour from the unit test; if you look at that example you will see 4 "parts" are created, two of them are then saved individually, then all 4 are saved as part of $robot->save() (lines 354 / 356), and then they test and show that each of the 4 parts has only been saved once.

I think it's actually me misunderstanding what the unit test was doing. I thought it was detecting that there was a part called "Part 1" and "Part 2" and so not inserting. What it's actually doing is noticing that those two parts have ID values, and so are not inserts.

My apologies. I'll rewrite my code to test each tag before adding to the tags array.

You could make this even simpler by overloading the save() method on Tag model and perform your unique test within the save itself. This way you don't need to call any extra methods and just go about your usual business as you would normally do.