Actually, the problem is that if isNewRecord always true, it means that Yii will use the INSERT instead of the UPDATE when saving the model to the database .. that is why you always get a duplicate pk error, even if it is compound.
Here is the official documentation for isNewRecord . So the problem is that you are using
$userCategory = new UserCategory;
So, to solve this problem, you need to find a record and evaluate it before you save it. You can also read the documentation here about the find() family of methods and their return value; the return values โโof find () are slightly different in nature:
find .. () returns the found record or NULL if the record is not found.
findAll .. () returns an array containing all the records found, or an empty array if no records were found.
You can use this return value to differentiate an existing primary key:
$userCategory = UserCategory::model()->findByAttributes(array('user_id '=>1,'category_id '=>15)); // if user does not exist, you need to create it if ($userCategory == NULL) { $userCategory = new UserCategory; $userCategory->user_id = 1; $userCategory->category_id = 15; } echo $userCategory->isNewRecord; //you will see the difference if it does exist or not exist $userCategory->last_access = Now(); $userCategory->save();
This ensures that the structure uses the INSERT or UPDATE statements correctly, avoiding duplicating the PK error you get.
Edit: Improved example code to correctly populate a record when it is new.
Snivs source share