Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Actually, the problem is that if <code>isNewRecord</code> is always true, it means that Yii is going to use an <code>INSERT</code> statement instead of an <code>UPDATE</code> statement when saving the model to the database.. that is why you always get the duplicate pk error, even if it's composite. </p> <p><a href="http://www.yiiframework.com/doc/api/1.1/CActiveRecord#getIsNewRecord-detail" rel="nofollow"><strong>Here</strong></a> is the official documentation about <code>IsNewRecord</code> . So, the problem is that you're using </p> <pre><code>$userCategory = new UserCategory; //Always a new record, tries to INSERT </code></pre> <p>So to resolve this you have to find the record and evaluate if it is found before saving it, instead. Documentation can also be read <a href="http://www.yiiframework.com/doc/api/1.1/CActiveRecord#find-detail" rel="nofollow"><strong>Here</strong></a> about the <code>find()</code> family of methods and their return value, the return values of the find() methods vary slightly on their nature:</p> <blockquote> <p>find..() returns the record found or <code>NULL</code> if no record is found.</p> <p>findAll..() returns an array containing all the records found or an empty array if no records are found.</p> </blockquote> <p>You can use this return value to differentiate wether a primary key exists or not:</p> <pre><code>$userCategory = UserCategory::model()-&gt;findByAttributes(array('user_id '=&gt;1,'category_id '=&gt;15)); // if user does not exist, you need to create it if ($userCategory == NULL) { $userCategory = new UserCategory; $userCategory-&gt;user_id = 1; $userCategory-&gt;category_id = 15; } echo $userCategory-&gt;isNewRecord; //you will see the difference if it does exist or not exist $userCategory-&gt;last_access = Now(); $userCategory-&gt;save(); </code></pre> <p>This will ensure that the framework uses the INSERT or UPDATE statement correctly, avoiding the duplicate PK error you're getting.</p> <p><strong>Edit:</strong> Enhanced the example code to properly populate the record when it's new.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload