multiple save in a loop and findByPk

Hi all

I am trying to do this :

all ids are ids that are not present in the db

$array = array(1,2,3);

foreach($array as $id) {


  //fetch model if it exists

  $model = ModelA->model()->findByPk($id);

  //if no record found

  if(is_null($model)) {

    $model = new modelA;


  $model->someAttribute = someValue;




if no record is found the code should create a new instance of modelA and INSERT it

this works on the first iteration of the loop

but after that

$model gets populated by the values saved on the first iteration

I tried to add $model->isNewRecord = true instead of unsetting $model

but this does not work either

can someone explain what I should be doing to achieve this ?

thanks a lot

Do you mean that in the second iteration the $model = ModelA->model()->findByPk($id); return a not null result?

Or that yii save a model in the db with differents id but same value for other attributes?

It has nothing to do with $model because you are assigning to it a new object for each iteration.

Does your 'someValue' change for each iteration?

you may want to try is_object() function instead of is_null()

hi all

yes SomeValue changes

what happens is that the call to findByPk returns the previous record (saved at the previous iteration)

my real case is a little bit different since the query ends up looking like this

SELECT * from ModelA where IS NULL

but I still would expect the query to return Null (since there are no record with id IS NULL)

but somehow the results are populated with the attributes of the object saved at the previous iteration including its newly created id

does that makes sense ?

Yii doesn't cache anything like this. Your code may have some problem. Could you paste complete code?

thanks for the answer

here is the code :

It seems to me you should use

if(!($artist = Artist::model()->findByPk($eventArtist['id'])))

I'll try it



when I was debugging, and following the record being populated, at some point after queryInternal the record got populated by the previous data