Yii Framework Forum: AR bug: setIsNewRecord leaves primaryKey value - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

AR bug: setIsNewRecord leaves primaryKey value Rate Topic: -----

#1 User is offline   vamp 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 181
  • Joined: 30-January 09

Posted 14 April 2010 - 07:33 AM

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

$link = new SomeArModel();
$link->setAttributes($baseAttributes,false);
foreach($pks as $N=>$id){
  $link->setIsNewRecord(true);
  $link->related_id=$id;
  $link->save();
}


on next iteration (N>0) appears an error:
Integrity constraint violation: 1062 Duplicate entry '...' for key 1
-Posted Image-
Thanks, you make me stronger!
0

#2 User is offline   Maurizio Domba Cerin 

  • Yii - Yesss It Is !!!
  • Yii
  • Group: Yii Dev Team
  • Posts: 4,359
  • Joined: 12-October 09
  • Location:Croatia

Posted 14 April 2010 - 01:11 PM

It's a "known" issue... take a look at a similar post http://www.yiiframew...__fromsearch__1

there is a workaround with setPrimaryKey()
Find more about me.... btw. Do you know your WAN IP?
0

#3 User is offline   creocoder 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 199
  • Joined: 09-March 09
  • Location:*.php

Posted 14 April 2010 - 05:55 PM

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;
    $link->setAttributes($baseAttributes,false);
    $link->related_id=$id;
    $link->save(false);
}


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.
No good, no bad, only consequence.
1

#4 User is offline   Mike 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 3,016
  • Joined: 06-October 08
  • Location:Upper Palatinate

Posted 15 April 2010 - 03:14 AM

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.
1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users