I know it’s little bit late answer but I hope someone can gain from my experience.
I ran into same problem and find out where the bug is. The problem is not in yout model relation definition but in way (order) you are saving the models in your controller.
Above method try to save main model with relateds together. This is allowed when you are upda-ting the main entry but not when you are creating new one. It’s because of this piece of code (ESaveRelatedBehavior.php line 215)
// Handle many_many relations, this check has to be done first, since CManyManyRelation extends CHasManyRelation
// The owner also needs to successfully saved, so that the foreign key can be determined
if ($relation instanceof CManyManyRelation && !$this->owner->isNewRecord)
So as the comment says "owner also needs to successfully saved" you must save owner model at first. You can do it like: