Reputation: 139
I need to save same model($modelcrite) multiple times after changing a id here is the code
protected function saveed($data1,$studentid,$modelcrite,$model)
{
$index = 0;
foreach ($data1 as $key => $value) {
$studentid[$index]=(string)$key;
$modelcrite->setAttribute('st_id',$key);
if ($modelcrite->validate()){
$modelcrite->setScenario('insert');
$modelcrite->save();
}
else {
$this->Delete($model->ass_id);
return FALSE;
}
$index=$index+1;
}
return TRUE;
}
but the problem is when second time save the $modelcrite value it is updating the database.I need to save it as new one
please can any one tell how can i do that.thank you.
Upvotes: 0
Views: 1716
Reputation: 11483
I believe that you confusion comes from the fact that an ActiveRecord model does not represent a table, but instead represents a row in the table. So changing the terminology a bit, when you pass in the new model(row) $modelcrite ActiveRecord recognizes that this is a new model(row), and the save performs an insert. At this point now Active record realizes that the model(row) exists in the table, and any additional saves against that model(row) will generate an update.
With that background in mind what you need to do is in your foreach loop create a new model for the insert, and set the attributes of the new model to $modelcrite, then set the student_id, then validate and save.
Something like this:
foreach ($data1 as $key => $value) {
$newModel = new CriteModel();
$newModel->attributes = $modelcrite->attributes;
$studentid[$index]=(string)$key;
$newModel->setAttribute('st_id',$key);
if ($newModel->validate()){
$newModel->save();
Upvotes: 1