save model with for loops

i have this code in my controller with create action ,user are entering multiple emails in textbox with comma separated ,i m exploding and saving then one by one but it is not saving in db only last record is not going

below is my code

public function actionCreate()

{


    $model = new InviteInfo();


    $this->performAjaxValidation($model);


    if ($model->load(Yii::$app->request->post())) {


             echo $emails=explode(',',$model->email);


      


         for($i=0;$i<count($emails);$i++){


                  $model->email=$emails[$i]; //exit;


                  $model->created_at=date('Y-m-d h:i:s');


                  $model->save();


             


        }


         


        return $this->redirect(['index']);


    } else {


        return $this->render('create', [


            'model' => $model,


        ]);


    }


}  

only second value is saving ,second loop is saving,first is not saving

what is wrong in this?

You are creating a single model. Within the loop, you are setting its property and save that away. As you are reusing that model, which has now a primary key assigned to it, all consecutive calls to [font="Courier New"]save()[/font] will be turned into [font="Courier New"]UPDATE[/font]s, not [font="Courier New"]INSERT[/font]s. So in the end you will effectively only have the very last address of your input saved.

Btw, have a look at the TimestampBehavior ;)




use yii\db\Expression;


public function actionCreate() {

    	$this->performAjaxValidation($model);

    	if ($model->load(Yii::$app->request->post())) {

        	$emails = explode(',',$model->email);

        	foreach ($emails as $email) {

 		         $model = new InviteInfo();

     	     	$model->email = trim($email);

 		         $model->created_at = new Expression('NOW()')

              	$model->save();

        	}

        	return $this->redirect(['index']);

    	} else {

        	return $this->render('create', ['model' => $model]);

    	}

  }



I wouldn’t use the behavior for this Id use dbcritera now. I say this because it gets called every time you call the model even if you’re just viewing it.

Please just create a new model on each iteration of your loop.