Skip to content

Commit 417a68e

Browse files
committed
fix #45: on saveAll() first delete removed models, then save the rest
1 parent 02527ad commit 417a68e

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed

RelationTrait.php

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -136,31 +136,21 @@ public function saveAll($skippedRelations = [])
136136
$relModel->$key = $this->$value;
137137
$notDeletedFK[$key] = $this->$value;
138138
}
139-
$relSave = $relModel->save();
140139

141-
if (!$relSave || !empty($relModel->errors)) {
142-
$relModelWords = Yii::t('app', Inflector::camel2words(StringHelper::basename($AQ->modelClass)));
143-
$index++;
144-
foreach ($relModel->errors as $validation) {
145-
foreach ($validation as $errorMsg) {
146-
$this->addError($name, "$relModelWords #$index : $errorMsg");
140+
//GET PK OF REL MODEL
141+
if ($isManyMany) {
142+
$mainPK = array_keys($link)[0];
143+
foreach ($relModel->primaryKey as $attr => $value) {
144+
if ($attr != $mainPK) {
145+
$notDeletedPK[$attr][] = $value;
147146
}
148147
}
149-
$error = true;
150148
} else {
151-
//GET PK OF REL MODEL
152-
if ($isManyMany) {
153-
$mainPK = array_keys($link)[0];
154-
foreach ($relModel->primaryKey as $attr => $value) {
155-
if ($attr != $mainPK) {
156-
$notDeletedPK[$attr][] = $value;
157-
}
158-
}
159-
} else {
160-
$notDeletedPK[] = $relModel->primaryKey;
161-
}
149+
$notDeletedPK[] = $relModel->primaryKey;
162150
}
151+
163152
}
153+
164154
if (!$isNewRecord) {
165155
//DELETE WITH 'NOT IN' PK MODEL & REL MODEL
166156
if ($isManyMany) {
@@ -197,6 +187,21 @@ public function saveAll($skippedRelations = [])
197187
}
198188
}
199189
}
190+
191+
foreach ($records as $index => $relModel) {
192+
$relSave = $relModel->save();
193+
194+
if (!$relSave || !empty($relModel->errors)) {
195+
$relModelWords = Yii::t('app', Inflector::camel2words(StringHelper::basename($AQ->modelClass)));
196+
$index++;
197+
foreach ($relModel->errors as $validation) {
198+
foreach ($validation as $errorMsg) {
199+
$this->addError($name, "$relModelWords #$index : $errorMsg");
200+
}
201+
}
202+
$error = true;
203+
}
204+
}
200205
} else {
201206
//Has One
202207
foreach ($link as $key => $value) {

0 commit comments

Comments
 (0)