Skip to content

Commit

Permalink
Improve update/insert models by id in import
Browse files Browse the repository at this point in the history
  • Loading branch information
ereminmdev committed Apr 13, 2021
1 parent 700b1b4 commit 04980f2
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions components/CrudImport.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@ public function import()
$fields = array_shift($rows);
array_shift($rows); // extract 2nd row

/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;

foreach ($rows as $idx => $row) {
$values = array_combine($fields, $row);
foreach ($values as $key => $value) {
Expand All @@ -107,11 +110,14 @@ public function import()

$this->prepareData($values);

/* @var $model ActiveRecord */
$model = new $this->modelClass;
$model = new $modelClass;

if ($id = ArrayHelper::getValue($values, 'id')) {
$model->setAttribute('id', $id);
$model->setIsNewRecord(false);
$model = $modelClass::findOne($id);
if ($model === null) {
$model = new $modelClass;
$model->setAttribute('id', $id);
}
}
$model->setAttributes($values);

Expand Down

0 comments on commit 04980f2

Please sign in to comment.