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