1 | <?php |
||||
2 | |||||
3 | namespace lhs\Yii2SaveRelationsBehavior; |
||||
4 | |||||
5 | use RuntimeException; |
||||
6 | use Yii; |
||||
7 | use yii\base\Behavior; |
||||
8 | use yii\base\Exception; |
||||
9 | use yii\base\ModelEvent; |
||||
10 | use yii\base\UnknownPropertyException; |
||||
11 | use yii\db\ActiveQuery; |
||||
12 | use yii\db\BaseActiveRecord; |
||||
13 | use yii\db\Exception as DbException; |
||||
14 | use yii\db\Transaction; |
||||
15 | use yii\helpers\ArrayHelper; |
||||
16 | use yii\helpers\Inflector; |
||||
17 | |||||
18 | /** |
||||
19 | * This Active Record Behavior allows to validate and save the Model relations when the save() method is invoked. |
||||
20 | * List of handled relations should be declared using the $relations parameter via an array of relation names. |
||||
21 | * @author albanjubert |
||||
22 | */ |
||||
23 | class SaveRelationsBehavior extends Behavior |
||||
24 | { |
||||
25 | |||||
26 | public $relations = []; |
||||
27 | private $_relations = []; |
||||
28 | private $_oldRelationValue = []; // Store initial relations value |
||||
29 | private $_newRelationValue = []; // Store update relations value |
||||
30 | private $_relationsSaveStarted = false; |
||||
31 | private $_transaction; |
||||
32 | |||||
33 | |||||
34 | private $_relationsScenario = []; |
||||
35 | private $_relationsExtraColumns = []; |
||||
36 | |||||
37 | //private $_relationsCascadeDelete = []; //TODO |
||||
38 | |||||
39 | /** |
||||
40 | * @inheritdoc |
||||
41 | */ |
||||
42 | 35 | public function init() |
|||
43 | { |
||||
44 | 35 | parent::init(); |
|||
45 | 35 | $allowedProperties = ['scenario', 'extraColumns']; |
|||
46 | 35 | foreach ($this->relations as $key => $value) { |
|||
47 | 34 | if (is_int($key)) { |
|||
48 | 34 | $this->_relations[] = $value; |
|||
49 | } else { |
||||
50 | 28 | $this->_relations[] = $key; |
|||
51 | 28 | if (is_array($value)) { |
|||
52 | 28 | foreach ($value as $propertyKey => $propertyValue) { |
|||
53 | 28 | if (in_array($propertyKey, $allowedProperties)) { |
|||
54 | 28 | $this->{'_relations' . ucfirst($propertyKey)}[$key] = $propertyValue; |
|||
55 | } else { |
||||
56 | 28 | throw new UnknownPropertyException('The relation property named ' . $propertyKey . ' is not supported'); |
|||
57 | } |
||||
58 | } |
||||
59 | } |
||||
60 | } |
||||
61 | } |
||||
62 | 35 | } |
|||
63 | |||||
64 | /** |
||||
65 | * @inheritdoc |
||||
66 | */ |
||||
67 | 34 | public function events() |
|||
68 | { |
||||
69 | return [ |
||||
70 | 34 | BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate', |
|||
71 | 34 | BaseActiveRecord::EVENT_AFTER_INSERT => 'afterSave', |
|||
72 | 34 | BaseActiveRecord::EVENT_AFTER_UPDATE => 'afterSave', |
|||
73 | ]; |
||||
74 | } |
||||
75 | |||||
76 | /** |
||||
77 | * Check if the behavior is attached to an Active Record |
||||
78 | * @param BaseActiveRecord $owner |
||||
79 | * @throws RuntimeException |
||||
80 | */ |
||||
81 | 35 | public function attach($owner) |
|||
82 | { |
||||
83 | 35 | if (!($owner instanceof BaseActiveRecord)) { |
|||
0 ignored issues
–
show
introduced
by
Loading history...
|
|||||
84 | 1 | throw new RuntimeException('Owner must be instance of yii\db\BaseActiveRecord'); |
|||
85 | } |
||||
86 | 34 | parent::attach($owner); |
|||
87 | 34 | } |
|||
88 | |||||
89 | /** |
||||
90 | * Override canSetProperty method to be able to detect if a relation setter is allowed. |
||||
91 | * Setter is allowed if the relation is declared in the `relations` parameter |
||||
92 | * @param string $name |
||||
93 | * @param boolean $checkVars |
||||
94 | * @return boolean |
||||
95 | */ |
||||
96 | 33 | public function canSetProperty($name, $checkVars = true) |
|||
97 | { |
||||
98 | 33 | if (in_array($name, $this->_relations) && $this->owner->getRelation($name, false)) { |
|||
0 ignored issues
–
show
The method
getRelation() does not exist on null .
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces. This is most likely a typographical error or the method has been renamed.
Loading history...
|
|||||
99 | 32 | return true; |
|||
100 | } |
||||
101 | 1 | return parent::canSetProperty($name, $checkVars); |
|||
102 | } |
||||
103 | |||||
104 | /** |
||||
105 | * Override __set method to be able to set relations values either by providing a model instance, |
||||
106 | * a primary key value or an associative array |
||||
107 | * @param string $name |
||||
108 | * @param mixed $value |
||||
109 | */ |
||||
110 | 32 | public function __set($name, $value) |
|||
111 | { |
||||
112 | 32 | if (in_array($name, $this->_relations)) { |
|||
113 | 32 | Yii::debug("Setting {$name} relation value", __METHOD__); |
|||
114 | 32 | if (!isset($this->_oldRelationValue[$name])) { |
|||
115 | 32 | if ($this->owner->isNewRecord) { |
|||
116 | 15 | if ($this->owner->getRelation($name)->multiple === true) { |
|||
117 | 7 | $this->_oldRelationValue[$name] = []; |
|||
118 | } else { |
||||
119 | 13 | $this->_oldRelationValue[$name] = null; |
|||
120 | } |
||||
121 | } else { |
||||
122 | 18 | $this->_oldRelationValue[$name] = $this->owner->{$name}; |
|||
123 | } |
||||
124 | } |
||||
125 | 32 | if ($this->owner->getRelation($name)->multiple === true) { |
|||
126 | 21 | $this->setMultipleRelation($name, $value); |
|||
127 | } else { |
||||
128 | 19 | $this->setSingleRelation($name, $value); |
|||
129 | } |
||||
130 | } |
||||
131 | 32 | } |
|||
132 | |||||
133 | /** |
||||
134 | * Set the named single relation with the given value |
||||
135 | * @param $name |
||||
136 | * @param $value |
||||
137 | */ |
||||
138 | 19 | protected function setSingleRelation($name, $value) |
|||
139 | { |
||||
140 | 19 | $relation = $this->owner->getRelation($name); |
|||
141 | 19 | if (!($value instanceof $relation->modelClass)) { |
|||
142 | 8 | $value = $this->processModelAsArray($value, $relation); |
|||
143 | } |
||||
144 | 19 | $this->_newRelationValue[$name] = $value; |
|||
145 | 19 | $this->owner->populateRelation($name, $value); |
|||
146 | 19 | } |
|||
147 | |||||
148 | /** |
||||
149 | * Set the named multiple relation with the given value |
||||
150 | * @param $name |
||||
151 | * @param $value |
||||
152 | */ |
||||
153 | 21 | protected function setMultipleRelation($name, $value) |
|||
154 | { |
||||
155 | 21 | $relation = $this->owner->getRelation($name); |
|||
156 | 21 | $newRelations = []; |
|||
157 | 21 | if (!is_array($value)) { |
|||
158 | 3 | if (!empty($value)) { |
|||
159 | 2 | $value = [$value]; |
|||
160 | } else { |
||||
161 | 1 | $value = []; |
|||
162 | } |
||||
163 | } |
||||
164 | 21 | foreach ($value as $entry) { |
|||
165 | 20 | if ($entry instanceof $relation->modelClass) { |
|||
166 | 15 | $newRelations[] = $entry; |
|||
167 | } else { |
||||
168 | // TODO handle this with one DB request to retrieve all models |
||||
169 | 9 | $newRelations[] = $this->processModelAsArray($entry, $relation); |
|||
170 | } |
||||
171 | } |
||||
172 | 21 | $this->_newRelationValue[$name] = $newRelations; |
|||
173 | 21 | $this->owner->populateRelation($name, $newRelations); |
|||
174 | 21 | } |
|||
175 | |||||
176 | /** |
||||
177 | * Get a BaseActiveRecord model using the given $data parameter. |
||||
178 | * $data could either be a model ID or an associative array representing model attributes => values |
||||
179 | * @param mixed $data |
||||
180 | * @param \yii\db\ActiveQuery $relation |
||||
181 | * @return BaseActiveRecord |
||||
182 | */ |
||||
183 | 13 | protected function processModelAsArray($data, $relation) |
|||
184 | { |
||||
185 | /** @var BaseActiveRecord $modelClass */ |
||||
186 | 13 | $modelClass = $relation->modelClass; |
|||
187 | // Get the related model foreign keys |
||||
188 | 13 | if (is_array($data)) { |
|||
189 | 9 | $fks = []; |
|||
190 | |||||
191 | // search PK |
||||
192 | 9 | foreach ($modelClass::primaryKey() as $modelAttribute) { |
|||
193 | 9 | if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) { |
|||
194 | 7 | $fks[$modelAttribute] = $data[$modelAttribute]; |
|||
195 | } else { |
||||
196 | 7 | $fks = []; |
|||
197 | 7 | break; |
|||
198 | } |
||||
199 | } |
||||
200 | 9 | if (empty($fks)) { |
|||
201 | // Get the right link definition |
||||
202 | 7 | if ($relation->via instanceof BaseActiveRecord) { |
|||
203 | /** @var BaseActiveRecord|array $viaQuery */ |
||||
204 | $viaQuery = $relation->via; |
||||
205 | $link = $viaQuery->link; |
||||
206 | 7 | } elseif (is_array($relation->via)) { |
|||
207 | 2 | list($viaName, $viaQuery) = $relation->via; |
|||
208 | 2 | $link = $viaQuery->link; |
|||
209 | } else { |
||||
210 | 5 | $link = $relation->link; |
|||
211 | } |
||||
212 | 7 | foreach ($link as $relatedAttribute => $modelAttribute) { |
|||
213 | 7 | if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) { |
|||
214 | 7 | $fks[$modelAttribute] = $data[$modelAttribute]; |
|||
215 | } |
||||
216 | } |
||||
217 | } |
||||
218 | } else { |
||||
219 | 4 | $fks = $data; |
|||
220 | } |
||||
221 | // Load existing model or create one if no key was provided and data is not empty |
||||
222 | /** @var BaseActiveRecord $relationModel */ |
||||
223 | 13 | $relationModel = null; |
|||
224 | 13 | if (!empty($fks)) { |
|||
225 | 8 | $relationModel = $modelClass::findOne($fks); |
|||
226 | } |
||||
227 | 13 | if (!($relationModel instanceof BaseActiveRecord) && !empty($data)) { |
|||
228 | 8 | $relationModel = new $modelClass; |
|||
229 | } |
||||
230 | 13 | if (($relationModel instanceof BaseActiveRecord) && is_array($data)) { |
|||
231 | 9 | $relationModel->setAttributes($data); |
|||
232 | } |
||||
233 | 13 | return $relationModel; |
|||
234 | } |
||||
235 | |||||
236 | /** |
||||
237 | * Before the owner model validation, save related models. |
||||
238 | * For `hasOne()` relations, set the according foreign keys of the owner model to be able to validate it |
||||
239 | * @param ModelEvent $event |
||||
240 | * @throws DbException |
||||
241 | * @throws \yii\base\InvalidConfigException |
||||
242 | */ |
||||
243 | 29 | public function beforeValidate(ModelEvent $event) |
|||
244 | { |
||||
245 | 29 | if ($this->_relationsSaveStarted === false && !empty($this->_oldRelationValue)) { |
|||
246 | /* @var $model BaseActiveRecord */ |
||||
247 | 29 | $model = $this->owner; |
|||
248 | 29 | if ($this->saveRelatedRecords($model, $event)) { |
|||
249 | // If relation is has_one, try to set related model attributes |
||||
250 | 27 | foreach ($this->_relations as $relationName) { |
|||
251 | 27 | if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
|||
252 | 27 | $relation = $model->getRelation($relationName); |
|||
253 | 27 | if ($relation->multiple === false && !empty($model->{$relationName})) { |
|||
254 | 15 | Yii::debug("Setting foreign keys for {$relationName}", __METHOD__); |
|||
255 | 15 | foreach ($relation->link as $relatedAttribute => $modelAttribute) { |
|||
256 | 15 | if ($model->{$modelAttribute} !== $model->{$relationName}->{$relatedAttribute}) { |
|||
257 | 15 | $model->{$modelAttribute} = $model->{$relationName}->{$relatedAttribute}; |
|||
258 | } |
||||
259 | } |
||||
260 | } |
||||
261 | } |
||||
262 | } |
||||
263 | } |
||||
264 | } |
||||
265 | 29 | } |
|||
266 | |||||
267 | /** |
||||
268 | * For each related model, try to save it first. |
||||
269 | * If set in the owner model, operation is done in a transactional way so if one of the models should not validate |
||||
270 | * or be saved, a rollback will occur., |
||||
271 | * This is done during the before validation process to be able to set the related foreign keys. |
||||
272 | * @param BaseActiveRecord $model |
||||
273 | * @param ModelEvent $event |
||||
274 | * @return bool |
||||
275 | * @throws DbException |
||||
276 | * @throws \yii\base\InvalidConfigException |
||||
277 | */ |
||||
278 | 29 | protected function saveRelatedRecords(BaseActiveRecord $model, ModelEvent $event) |
|||
279 | { |
||||
280 | if ( |
||||
281 | 29 | method_exists($model, 'isTransactional') |
|||
282 | 29 | && is_null($model->getDb()->transaction) |
|||
283 | && ( |
||||
284 | 29 | ($model->isNewRecord && $model->isTransactional($model::OP_INSERT)) |
|||
285 | 21 | || (!$model->isNewRecord && $model->isTransactional($model::OP_UPDATE)) |
|||
286 | 6 | || $model->isTransactional($model::OP_ALL) |
|||
287 | ) |
||||
288 | ) { |
||||
289 | 23 | $this->_transaction = $model->getDb()->beginTransaction(); |
|||
290 | } |
||||
291 | try { |
||||
292 | 29 | foreach ($this->_relations as $relationName) { |
|||
293 | 29 | if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
|||
294 | /** @var ActiveQuery $relation */ |
||||
295 | 29 | $relation = $model->getRelation($relationName); |
|||
296 | 29 | if (!empty($model->{$relationName})) { |
|||
297 | 27 | if ($relation->multiple === false) { |
|||
298 | 17 | $this->_prepareHasOneRelation($model, $relationName, $event); |
|||
299 | } else { |
||||
300 | 18 | $this->_prepareHasManyRelation($model, $relationName); |
|||
301 | } |
||||
302 | } |
||||
303 | } |
||||
304 | } |
||||
305 | 27 | if (!$event->isValid) { |
|||
306 | throw new Exception('One of the related model could not be validated'); |
||||
307 | } |
||||
308 | 2 | } catch (Exception $e) { |
|||
309 | 2 | Yii::warning(get_class($e) . ' was thrown while saving related records during beforeValidate event: ' . $e->getMessage(), __METHOD__); |
|||
310 | 2 | $this->_rollback(); |
|||
311 | 2 | $model->addError($model->formName(), $e->getMessage()); |
|||
312 | 2 | $event->isValid = false; // Stop saving, something went wrong |
|||
313 | 2 | return false; |
|||
314 | } |
||||
315 | 27 | return true; |
|||
316 | } |
||||
317 | |||||
318 | /** |
||||
319 | * Validate a relation model and add an error message to owner model attribute if needed |
||||
320 | * @param string $pettyRelationName |
||||
321 | * @param string $relationName |
||||
322 | * @param BaseActiveRecord $relationModel |
||||
323 | */ |
||||
324 | 27 | protected function validateRelationModel($pettyRelationName, $relationName, BaseActiveRecord $relationModel) |
|||
325 | { |
||||
326 | /** @var BaseActiveRecord $model */ |
||||
327 | 27 | $model = $this->owner; |
|||
328 | 27 | if (!is_null($relationModel) && ($relationModel->isNewRecord || count($relationModel->getDirtyAttributes()))) { |
|||
329 | 19 | if (array_key_exists($relationName, $this->_relationsScenario)) { |
|||
330 | 7 | $relationModel->setScenario($this->_relationsScenario[$relationName]); |
|||
331 | } |
||||
332 | 19 | Yii::debug("Validating {$pettyRelationName} relation model using " . $relationModel->scenario . ' scenario', __METHOD__); |
|||
333 | 19 | if (!$relationModel->validate()) { |
|||
334 | 4 | $this->_addError($relationModel, $model, $relationName, $pettyRelationName); |
|||
335 | } |
||||
336 | |||||
337 | } |
||||
338 | 27 | } |
|||
339 | |||||
340 | /** |
||||
341 | * Attach errors to owner relational attributes |
||||
342 | * @param $relationModel |
||||
343 | * @param $owner |
||||
344 | * @param $relationName |
||||
345 | * @param $pettyRelationName |
||||
346 | */ |
||||
347 | 5 | private function _addError($relationModel, $owner, $relationName, $pettyRelationName) |
|||
348 | { |
||||
349 | 5 | foreach ($relationModel->errors as $attributeErrors) { |
|||
350 | 5 | foreach ($attributeErrors as $error) { |
|||
351 | 5 | $owner->addError($relationName, "{$pettyRelationName}: {$error}"); |
|||
352 | } |
||||
353 | } |
||||
354 | 5 | } |
|||
355 | |||||
356 | /** |
||||
357 | * Rollback transaction if any |
||||
358 | * @throws DbException |
||||
359 | */ |
||||
360 | 3 | private function _rollback() |
|||
361 | { |
||||
362 | 3 | if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) { |
|||
363 | 2 | $this->_transaction->rollBack(); // If anything goes wrong, transaction will be rolled back |
|||
364 | 2 | Yii::info('Rolling back', __METHOD__); |
|||
365 | } |
||||
366 | 3 | } |
|||
367 | |||||
368 | /** |
||||
369 | * Link the related models. |
||||
370 | * If the models have not been changed, nothing will be done. |
||||
371 | * Related records will be linked to the owner model using the BaseActiveRecord `link()` method. |
||||
372 | * @throws Exception |
||||
373 | */ |
||||
374 | 27 | public function afterSave() |
|||
375 | { |
||||
376 | 27 | if ($this->_relationsSaveStarted === false) { |
|||
377 | /** @var BaseActiveRecord $owner */ |
||||
378 | 27 | $owner = $this->owner; |
|||
379 | 27 | $this->_relationsSaveStarted = true; |
|||
380 | // Populate relations with updated values |
||||
381 | 27 | foreach ($this->_newRelationValue as $name => $value) { |
|||
382 | 27 | $this->owner->populateRelation($name, $value); |
|||
383 | } |
||||
384 | try { |
||||
385 | 27 | foreach ($this->_relations as $relationName) { |
|||
386 | 27 | if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
|||
387 | 27 | Yii::debug("Linking {$relationName} relation", __METHOD__); |
|||
388 | /** @var ActiveQuery $relation */ |
||||
389 | 27 | $relation = $owner->getRelation($relationName); |
|||
390 | 27 | if ($relation->multiple === true) { // Has many relation |
|||
391 | 18 | $this->_afterSaveHasManyRelation($relationName); |
|||
392 | } else { // Has one relation |
||||
393 | 17 | $this->_afterSaveHasOneRelation($relationName); |
|||
394 | } |
||||
395 | 27 | unset($this->_oldRelationValue[$relationName]); |
|||
396 | } |
||||
397 | } |
||||
398 | 1 | } catch (Exception $e) { |
|||
399 | 1 | Yii::warning(get_class($e) . ' was thrown while saving related records during afterSave event: ' . $e->getMessage(), __METHOD__); |
|||
400 | 1 | $this->_rollback(); |
|||
401 | /*** |
||||
402 | * Sadly mandatory because the error occurred during afterSave event |
||||
403 | * and we don't want the user/developper not to be aware of the issue. |
||||
404 | ***/ |
||||
405 | 1 | throw $e; |
|||
406 | } |
||||
407 | 27 | $owner->refresh(); |
|||
408 | 27 | $this->_relationsSaveStarted = false; |
|||
409 | 27 | if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) { |
|||
410 | 21 | $this->_transaction->commit(); |
|||
411 | } |
||||
412 | } |
||||
413 | 27 | } |
|||
414 | |||||
415 | /** |
||||
416 | * Return array of columns to save to the junction table for a related model having a many-to-many relation. |
||||
417 | * @param string $relationName |
||||
418 | * @param BaseActiveRecord $model |
||||
419 | * @return array |
||||
420 | * @throws \RuntimeException |
||||
421 | */ |
||||
422 | 14 | private function _getJunctionTableColumns($relationName, $model) |
|||
423 | { |
||||
424 | 14 | $junctionTableColumns = []; |
|||
425 | 14 | if (array_key_exists($relationName, $this->_relationsExtraColumns)) { |
|||
426 | 1 | if (is_callable($this->_relationsExtraColumns[$relationName])) { |
|||
427 | 1 | $junctionTableColumns = $this->_relationsExtraColumns[$relationName]($model); |
|||
428 | } elseif (is_array($this->_relationsExtraColumns[$relationName])) { |
||||
429 | $junctionTableColumns = $this->_relationsExtraColumns[$relationName]; |
||||
430 | } |
||||
431 | 1 | if (!is_array($junctionTableColumns)) { |
|||
432 | throw new RuntimeException( |
||||
433 | 'Junction table columns definition must return an array, got ' . gettype($junctionTableColumns) |
||||
434 | ); |
||||
435 | } |
||||
436 | } |
||||
437 | 14 | return $junctionTableColumns; |
|||
438 | } |
||||
439 | |||||
440 | /** |
||||
441 | * Compute the difference between two set of records using primary keys "tokens" |
||||
442 | * If third parameter is set to true all initial related records will be marked for removal even if their |
||||
443 | * properties did not change. This can be handy in a many-to-many relation involving a junction table. |
||||
444 | * @param BaseActiveRecord[] $initialRelations |
||||
445 | * @param BaseActiveRecord[] $updatedRelations |
||||
446 | * @param bool $forceSave |
||||
447 | * @return array |
||||
448 | */ |
||||
449 | 17 | private function _computePkDiff($initialRelations, $updatedRelations, $forceSave = false) |
|||
450 | { |
||||
451 | // Compute differences between initial relations and the current ones |
||||
452 | $oldPks = ArrayHelper::getColumn($initialRelations, function (BaseActiveRecord $model) { |
||||
453 | 13 | return implode('-', $model->getPrimaryKey(true)); |
|||
454 | 17 | }); |
|||
455 | $newPks = ArrayHelper::getColumn($updatedRelations, function (BaseActiveRecord $model) { |
||||
456 | 13 | return implode('-', $model->getPrimaryKey(true)); |
|||
457 | 17 | }); |
|||
458 | 17 | if ($forceSave) { |
|||
459 | 1 | $addedPks = $newPks; |
|||
460 | 1 | $deletedPks = $oldPks; |
|||
461 | } else { |
||||
462 | 16 | $identicalPks = array_intersect($oldPks, $newPks); |
|||
463 | 16 | $addedPks = array_values(array_diff($newPks, $identicalPks)); |
|||
464 | 16 | $deletedPks = array_values(array_diff($oldPks, $identicalPks)); |
|||
465 | } |
||||
466 | 17 | return [$addedPks, $deletedPks]; |
|||
467 | } |
||||
468 | |||||
469 | /** |
||||
470 | * Populates relations with input data |
||||
471 | * @param array $data |
||||
472 | */ |
||||
473 | 4 | public function loadRelations($data) |
|||
474 | { |
||||
475 | /** @var BaseActiveRecord $model */ |
||||
476 | 4 | $model = $this->owner; |
|||
477 | 4 | foreach ($this->_relations as $relationName) { |
|||
478 | 4 | $relation = $model->getRelation($relationName); |
|||
479 | 4 | $modelClass = $relation->modelClass; |
|||
480 | /** @var ActiveQuery $relationalModel */ |
||||
481 | 4 | $relationalModel = new $modelClass; |
|||
482 | 4 | $formName = $relationalModel->formName(); |
|||
483 | 4 | if (array_key_exists($formName, $data)) { |
|||
484 | 4 | $model->{$relationName} = $data[$formName]; |
|||
485 | } |
||||
486 | } |
||||
487 | 4 | } |
|||
488 | |||||
489 | /** |
||||
490 | * @param $relationName |
||||
491 | * @throws DbException |
||||
492 | */ |
||||
493 | 18 | public function _afterSaveHasManyRelation($relationName) |
|||
494 | { |
||||
495 | /** @var BaseActiveRecord $owner */ |
||||
496 | 18 | $owner = $this->owner; |
|||
497 | 18 | $relation = $owner->getRelation($relationName); |
|||
498 | |||||
499 | // Process new relations |
||||
500 | 18 | $existingRecords = []; |
|||
501 | /** @var ActiveQuery $relationModel */ |
||||
502 | 18 | foreach ($owner->{$relationName} as $i => $relationModel) { |
|||
503 | 18 | if ($relationModel->isNewRecord) { |
|||
504 | 10 | if (!empty($relation->via)) { |
|||
505 | 9 | if ($relationModel->validate()) { |
|||
506 | 9 | $relationModel->save(); |
|||
507 | } else { |
||||
508 | 1 | $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}"; |
|||
509 | 1 | $this->_addError($relationModel, $owner, $relationName, $pettyRelationName); |
|||
510 | 1 | throw new DbException("Related record {$pettyRelationName} could not be saved."); |
|||
511 | } |
||||
512 | } |
||||
513 | 10 | $junctionTableColumns = $this->_getJunctionTableColumns($relationName, $relationModel); |
|||
514 | 10 | $owner->link($relationName, $relationModel, $junctionTableColumns); |
|||
515 | } else { |
||||
516 | 13 | $existingRecords[] = $relationModel; |
|||
517 | } |
||||
518 | 18 | if (count($relationModel->dirtyAttributes)) { |
|||
519 | 4 | if ($relationModel->validate()) { |
|||
520 | 4 | $relationModel->save(); |
|||
521 | } else { |
||||
522 | $pettyRelationName = Inflector::camel2words($relationName, true); |
||||
523 | $this->_addError($relationModel, $owner, $relationName, $pettyRelationName); |
||||
524 | throw new DbException("Related record {$pettyRelationName} could not be saved."); |
||||
525 | } |
||||
526 | } |
||||
527 | } |
||||
528 | 17 | $junctionTablePropertiesUsed = array_key_exists($relationName, $this->_relationsExtraColumns); |
|||
529 | |||||
530 | // Process existing added and deleted relations |
||||
531 | 17 | list($addedPks, $deletedPks) = $this->_computePkDiff( |
|||
532 | 17 | $this->_oldRelationValue[$relationName], |
|||
533 | 17 | $existingRecords, |
|||
534 | 17 | $junctionTablePropertiesUsed |
|||
535 | ); |
||||
536 | |||||
537 | // Deleted relations |
||||
538 | $initialModels = ArrayHelper::index($this->_oldRelationValue[$relationName], function (BaseActiveRecord $model) { |
||||
539 | 13 | return implode('-', $model->getPrimaryKey(true)); |
|||
540 | 17 | }); |
|||
541 | 17 | $initialRelations = $owner->{$relationName}; |
|||
542 | 17 | foreach ($deletedPks as $key) { |
|||
543 | 2 | $owner->unlink($relationName, $initialModels[$key], true); |
|||
544 | } |
||||
545 | |||||
546 | // Added relations |
||||
547 | 17 | $actualModels = ArrayHelper::index( |
|||
548 | 17 | $junctionTablePropertiesUsed ? $initialRelations : $owner->{$relationName}, |
|||
549 | 17 | function (BaseActiveRecord $model) { |
|||
550 | 17 | return implode('-', $model->getPrimaryKey(true)); |
|||
551 | 17 | } |
|||
552 | ); |
||||
553 | 17 | foreach ($addedPks as $key) { |
|||
554 | 4 | $junctionTableColumns = $this->_getJunctionTableColumns($relationName, $actualModels[$key]); |
|||
555 | 4 | $owner->link($relationName, $actualModels[$key], $junctionTableColumns); |
|||
556 | } |
||||
557 | 17 | } |
|||
558 | |||||
559 | /** |
||||
560 | * @param $relationName |
||||
561 | * @throws \yii\base\InvalidCallException |
||||
562 | */ |
||||
563 | 17 | private function _afterSaveHasOneRelation($relationName) |
|||
564 | { |
||||
565 | /** @var BaseActiveRecord $owner */ |
||||
566 | 17 | $owner = $this->owner; |
|||
567 | |||||
568 | 17 | if ($this->_oldRelationValue[$relationName] !== $owner->{$relationName}) { |
|||
569 | 14 | if ($owner->{$relationName} instanceof BaseActiveRecord) { |
|||
570 | 13 | $owner->link($relationName, $owner->{$relationName}); |
|||
571 | } else { |
||||
572 | 1 | if ($this->_oldRelationValue[$relationName] instanceof BaseActiveRecord) { |
|||
573 | 1 | $owner->unlink($relationName, $this->_oldRelationValue[$relationName]); |
|||
574 | } |
||||
575 | } |
||||
576 | } |
||||
577 | 17 | if ($owner->{$relationName} instanceof BaseActiveRecord) { |
|||
578 | 15 | $owner->{$relationName}->save(); |
|||
579 | } |
||||
580 | 17 | } |
|||
581 | |||||
582 | /** |
||||
583 | * @param BaseActiveRecord $model |
||||
584 | * @param $relationName |
||||
585 | */ |
||||
586 | 18 | private function _prepareHasManyRelation(BaseActiveRecord $model, $relationName) |
|||
587 | { |
||||
588 | /** @var BaseActiveRecord $relationModel */ |
||||
589 | 18 | foreach ($model->{$relationName} as $i => $relationModel) { |
|||
590 | 18 | $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}"; |
|||
591 | 18 | $this->validateRelationModel($pettyRelationName, $relationName, $relationModel); |
|||
592 | } |
||||
593 | 18 | } |
|||
594 | |||||
595 | /** |
||||
596 | * @param BaseActiveRecord $model |
||||
597 | * @param ModelEvent $event |
||||
598 | * @param $relationName |
||||
599 | */ |
||||
600 | 17 | private function _prepareHasOneRelation(BaseActiveRecord $model, $relationName, ModelEvent $event) |
|||
601 | { |
||||
602 | /** @var ActiveQuery $relation */ |
||||
603 | 17 | $relation = $model->getRelation($relationName); |
|||
604 | 17 | $relationModel = $model->{$relationName}; |
|||
605 | 17 | $p1 = $model->isPrimaryKey(array_keys($relation->link)); |
|||
606 | 17 | $p2 = $relationModel::isPrimaryKey(array_values($relation->link)); |
|||
607 | 17 | $pettyRelationName = Inflector::camel2words($relationName, true); |
|||
608 | 17 | if ($relationModel->getIsNewRecord() && $p1 && !$p2) { |
|||
609 | // Save Has one relation new record |
||||
610 | 10 | $this->validateRelationModel($pettyRelationName, $relationName, $model->{$relationName}); |
|||
611 | 10 | if ($event->isValid && (count($model->dirtyAttributes) || $model->{$relationName}->isNewRecord)) { |
|||
612 | 10 | Yii::debug("Saving {$pettyRelationName} relation model", __METHOD__); |
|||
613 | 10 | $model->{$relationName}->save(false); |
|||
614 | } |
||||
615 | } else { |
||||
616 | 10 | $this->validateRelationModel($pettyRelationName, $relationName, $relationModel); |
|||
617 | } |
||||
618 | 15 | } |
|||
619 | } |
||||
620 |