Save In Loop

i am tring to save model in loop , but it will save only 1 record not more

this is my code:




        foreach($UsersList as $User){

            self::model()->UserID = $User->UserID;

            self::model()->TXN = 1;

            self::model()->Remarks = 'Description';

            self::model()->Amount = 20;

            self::model()->Date = time();

            self::model()->Type = 1;

            self::model()->save();

            self::model()->isNewRecord = true;

            //echo "isNewRecord?".self::model()->isNewRecord; 

            unset(self::model()->ID);

        }

the function is inside same Model , i am doing


self::model()->isNewRecord = true;

unset(self::model()->ID);

but still one record will save , i have same code and it’s working but inside the model no

Please advise

Create a new model in the loop




        foreach($UsersList as $User){

            $model = new $className(null);

            $model->UserID = $User->UserID;

            $model->TXN = 1;

            $model)->Remarks = 'Description';

            $model->Amount = 20;

            $model->Date = time();

            $model->Type = 1;

            $model->save();

        }

Create new model in a loop? mean each time create new object?

are you sure this is the solution ?

Yes. But what is the trouble? This is still your variable $model.


   self::model()->UserID = $User->UserID;

            self::model()->TXN = 1;

            self::model()->Remarks = 'Description';

            self::model()->Amount = 20;



You don’t know php or other C-like language if you are doing so. :: means static method or variable.


self::model()->TXN = 1;

is like


5+7;

or other expressions. It does not store data. You need variables to do it.

The way to solve your issue exists try and find it. Or try to rewrite your code storing models data in variable. At first you need


$model = new Class();

outside the loop.

Ps: if you need good perfomance, AR is bad choice. Use Yii::app()->db->schema->commandBuilder->createMultipleInsertCommand() for your case. Available in latest version of Yii.