AR bug: setIsNewRecord leaves primaryKey value

next code works once (count($pks) > 1):

$link = new SomeArModel();


foreach($pks as $N=>$id){





on next iteration (N>0) appears an error:

Integrity constraint violation: 1062 Duplicate entry ‘…’ for key 1

It’s a “known” issue… take a look at a similar post

there is a workaround with setPrimaryKey()

Assumed, that it’s by design. New record in DB == new AR object to ensure all behaviors work out as expected. AR::setIsNewRecord(true) used here looks like dirty hack. Why not change code to:

foreach($pks as $N=>$id)


    $link=new SomeArModel;





What reason to do like you shown? If the goal is speed, use DAO. With DAO you can generate more effective SQL using massive INSERT syntax:

INSERT INTO table(c1,c2,c3) VALUES(v1,v2,v3),(v4,v5,v6),(v7,v8,v9),...,(vx,vy,vz);

CActiveRecord anyway did not do this for you, if it’s natural “active record pattern” by design.

Agree to creocoder. The code above is too obscure. creocoders example is much more understandable.

Keep in mind: If we want AR to handle all these rare situations, that could be avoided in the first place, AR’s code will get bloated even more and make AR slower.