Issues (915)

framework/db/BaseActiveRecord.php (1 issue)

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\db;
10
11
use Yii;
12
use yii\base\InvalidArgumentException;
13
use yii\base\InvalidCallException;
14
use yii\base\InvalidConfigException;
15
use yii\base\InvalidParamException;
16
use yii\base\Model;
17
use yii\base\ModelEvent;
18
use yii\base\NotSupportedException;
19
use yii\base\UnknownMethodException;
20
use yii\helpers\ArrayHelper;
21
22
/**
23
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
24
 *
25
 * See [[\yii\db\ActiveRecord]] for a concrete implementation.
26
 *
27
 * @property-read array $dirtyAttributes The changed attribute values (name-value pairs).
28
 * @property bool $isNewRecord Whether the record is new and should be inserted when calling [[save()]].
29
 * @property array $oldAttributes The old attribute values (name-value pairs). Note that the type of this
30
 * property differs in getter and setter. See [[getOldAttributes()]] and [[setOldAttributes()]] for details.
31
 * @property-read mixed $oldPrimaryKey The old primary key value. An array (column name => column value) is
32
 * returned if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be
33
 * returned if the key value is null).
34
 * @property-read mixed $primaryKey The primary key value. An array (column name => column value) is returned
35
 * if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned
36
 * if the key value is null).
37
 * @property-read array $relatedRecords An array of related records indexed by relation names.
38
 *
39
 * @author Qiang Xue <[email protected]>
40
 * @author Carsten Brandt <[email protected]>
41
 * @since 2.0
42
 */
43
abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
44
{
45
    /**
46
     * @event Event an event that is triggered when the record is initialized via [[init()]].
47
     */
48
    const EVENT_INIT = 'init';
49
    /**
50
     * @event Event an event that is triggered after the record is created and populated with query result.
51
     */
52
    const EVENT_AFTER_FIND = 'afterFind';
53
    /**
54
     * @event ModelEvent an event that is triggered before inserting a record.
55
     * You may set [[ModelEvent::isValid]] to be `false` to stop the insertion.
56
     */
57
    const EVENT_BEFORE_INSERT = 'beforeInsert';
58
    /**
59
     * @event AfterSaveEvent an event that is triggered after a record is inserted.
60
     */
61
    const EVENT_AFTER_INSERT = 'afterInsert';
62
    /**
63
     * @event ModelEvent an event that is triggered before updating a record.
64
     * You may set [[ModelEvent::isValid]] to be `false` to stop the update.
65
     */
66
    const EVENT_BEFORE_UPDATE = 'beforeUpdate';
67
    /**
68
     * @event AfterSaveEvent an event that is triggered after a record is updated.
69
     */
70
    const EVENT_AFTER_UPDATE = 'afterUpdate';
71
    /**
72
     * @event ModelEvent an event that is triggered before deleting a record.
73
     * You may set [[ModelEvent::isValid]] to be `false` to stop the deletion.
74
     */
75
    const EVENT_BEFORE_DELETE = 'beforeDelete';
76
    /**
77
     * @event Event an event that is triggered after a record is deleted.
78
     */
79
    const EVENT_AFTER_DELETE = 'afterDelete';
80
    /**
81
     * @event Event an event that is triggered after a record is refreshed.
82
     * @since 2.0.8
83
     */
84
    const EVENT_AFTER_REFRESH = 'afterRefresh';
85
86
    /**
87
     * @var array attribute values indexed by attribute names
88
     */
89
    private $_attributes = [];
90
    /**
91
     * @var array|null old attribute values indexed by attribute names.
92
     * This is `null` if the record [[isNewRecord|is new]].
93
     */
94
    private $_oldAttributes;
95
    /**
96
     * @var array related models indexed by the relation names
97
     */
98
    private $_related = [];
99
    /**
100
     * @var array relation names indexed by their link attributes
101
     */
102
    private $_relationsDependencies = [];
103
104
105
    /**
106
     * {@inheritdoc}
107
     * @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches.
108
     */
109 202
    public static function findOne($condition)
110
    {
111 202
        return static::findByCondition($condition)->one();
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     * @return static[] an array of ActiveRecord instances, or an empty array if nothing matches.
117
     */
118 6
    public static function findAll($condition)
119
    {
120 6
        return static::findByCondition($condition)->all();
121
    }
122
123
    /**
124
     * Finds ActiveRecord instance(s) by the given condition.
125
     * This method is internally called by [[findOne()]] and [[findAll()]].
126
     * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
127
     * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
128
     * @throws InvalidConfigException if there is no primary key defined
129
     * @internal
130
     */
131
    protected static function findByCondition($condition)
132
    {
133
        $query = static::find();
134
135
        if (!ArrayHelper::isAssociative($condition) && !$condition instanceof ExpressionInterface) {
136
            // query by primary key
137
            $primaryKey = static::primaryKey();
138
            if (isset($primaryKey[0])) {
139
                // if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values
140
                $condition = [$primaryKey[0] => is_array($condition) ? array_values($condition) : $condition];
141
            } else {
142
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
143
            }
144
        }
145
146
        return $query->andWhere($condition);
147
    }
148
149
    /**
150
     * Updates the whole table using the provided attribute values and conditions.
151
     *
152
     * For example, to change the status to be 1 for all customers whose status is 2:
153
     *
154
     * ```php
155
     * Customer::updateAll(['status' => 1], 'status = 2');
156
     * ```
157
     *
158
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
159
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
160
     * Please refer to [[Query::where()]] on how to specify this parameter.
161
     * @return int the number of rows updated
162
     * @throws NotSupportedException if not overridden
163
     */
164
    public static function updateAll($attributes, $condition = '')
165
    {
166
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
167
    }
168
169
    /**
170
     * Updates the whole table using the provided counter changes and conditions.
171
     *
172
     * For example, to increment all customers' age by 1,
173
     *
174
     * ```php
175
     * Customer::updateAllCounters(['age' => 1]);
176
     * ```
177
     *
178
     * @param array $counters the counters to be updated (attribute name => increment value).
179
     * Use negative values if you want to decrement the counters.
180
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
181
     * Please refer to [[Query::where()]] on how to specify this parameter.
182
     * @return int the number of rows updated
183
     * @throws NotSupportedException if not overrided
184
     */
185
    public static function updateAllCounters($counters, $condition = '')
186
    {
187
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
188
    }
189
190
    /**
191
     * Deletes rows in the table using the provided conditions.
192
     * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
193
     *
194
     * For example, to delete all customers whose status is 3:
195
     *
196
     * ```php
197
     * Customer::deleteAll('status = 3');
198
     * ```
199
     *
200
     * @param string|array|null $condition the conditions that will be put in the WHERE part of the DELETE SQL.
201
     * Please refer to [[Query::where()]] on how to specify this parameter.
202
     * @return int the number of rows deleted
203
     * @throws NotSupportedException if not overridden.
204
     */
205
    public static function deleteAll($condition = null)
206
    {
207
        throw new NotSupportedException(__METHOD__ . ' is not supported.');
208
    }
209
210
    /**
211
     * Returns the name of the column that stores the lock version for implementing optimistic locking.
212
     *
213
     * Optimistic locking allows multiple users to access the same record for edits and avoids
214
     * potential conflicts. In case when a user attempts to save the record upon some staled data
215
     * (because another user has modified the data), a [[StaleObjectException]] exception will be thrown,
216
     * and the update or deletion is skipped.
217
     *
218
     * Optimistic locking is only supported by [[update()]] and [[delete()]].
219
     *
220
     * To use Optimistic locking:
221
     *
222
     * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`.
223
     *    Override this method to return the name of this column.
224
     * 2. Ensure the version value is submitted and loaded to your model before any update or delete.
225
     *    Or add [[\yii\behaviors\OptimisticLockBehavior|OptimisticLockBehavior]] to your model
226
     *    class in order to automate the process.
227
     * 3. In the Web form that collects the user input, add a hidden field that stores
228
     *    the lock version of the record being updated.
229
     * 4. In the controller action that does the data updating, try to catch the [[StaleObjectException]]
230
     *    and implement necessary business logic (e.g. merging the changes, prompting stated data)
231
     *    to resolve the conflict.
232
     *
233
     * @return string|null the column name that stores the lock version of a table row.
234
     * If `null` is returned (default implemented), optimistic locking will not be supported.
235
     */
236 37
    public function optimisticLock()
237
    {
238 37
        return null;
239
    }
240
241
    /**
242
     * {@inheritdoc}
243
     */
244 3
    public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
245
    {
246 3
        if (parent::canGetProperty($name, $checkVars, $checkBehaviors)) {
247 3
            return true;
248
        }
249
250
        try {
251 3
            return $this->hasAttribute($name);
252
        } catch (\Exception $e) {
253
            // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used
254
            return false;
255
        }
256
    }
257
258
    /**
259
     * {@inheritdoc}
260
     */
261 9
    public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
262
    {
263 9
        if (parent::canSetProperty($name, $checkVars, $checkBehaviors)) {
264 6
            return true;
265
        }
266
267
        try {
268 3
            return $this->hasAttribute($name);
269
        } catch (\Exception $e) {
270
            // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used
271
            return false;
272
        }
273
    }
274
275
    /**
276
     * PHP getter magic method.
277
     * This method is overridden so that attributes and related objects can be accessed like properties.
278
     *
279
     * @param string $name property name
280
     * @throws InvalidArgumentException if relation name is wrong
281
     * @return mixed property value
282
     * @see getAttribute()
283
     */
284 465
    public function __get($name)
285
    {
286 465
        if (array_key_exists($name, $this->_attributes)) {
287 441
            return $this->_attributes[$name];
288
        }
289
290 237
        if ($this->hasAttribute($name)) {
291 44
            return null;
292
        }
293
294 214
        if (array_key_exists($name, $this->_related)) {
295 133
            return $this->_related[$name];
296
        }
297 139
        $value = parent::__get($name);
298 133
        if ($value instanceof ActiveQueryInterface) {
299 88
            $this->setRelationDependencies($name, $value);
300 88
            return $this->_related[$name] = $value->findFor($name, $this);
301
        }
302
303 54
        return $value;
304
    }
305
306
    /**
307
     * PHP setter magic method.
308
     * This method is overridden so that AR attributes can be accessed like properties.
309
     * @param string $name property name
310
     * @param mixed $value property value
311
     */
312 304
    public function __set($name, $value)
313
    {
314 304
        if ($this->hasAttribute($name)) {
315
            if (
316 304
                !empty($this->_relationsDependencies[$name])
317 304
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
318
            ) {
319 15
                $this->resetDependentRelations($name);
320
            }
321 304
            $this->_attributes[$name] = $value;
322
        } else {
323 6
            parent::__set($name, $value);
324
        }
325
    }
326
327
    /**
328
     * Checks if a property value is null.
329
     * This method overrides the parent implementation by checking if the named attribute is `null` or not.
330
     * @param string $name the property name or the event name
331
     * @return bool whether the property value is null
332
     */
333 251
    public function __isset($name)
334
    {
335
        try {
336 251
            return $this->__get($name) !== null;
337 10
        } catch (\Exception $t) {
338 7
            return false;
339 3
        } catch (\Throwable $e) {
340 3
            return false;
341
        }
342
    }
343
344
    /**
345
     * Sets a component property to be null.
346
     * This method overrides the parent implementation by clearing
347
     * the specified attribute value.
348
     * @param string $name the property name or the event name
349
     */
350 15
    public function __unset($name)
351
    {
352 15
        if ($this->hasAttribute($name)) {
353 9
            unset($this->_attributes[$name]);
354 9
            if (!empty($this->_relationsDependencies[$name])) {
355 9
                $this->resetDependentRelations($name);
356
            }
357 6
        } elseif (array_key_exists($name, $this->_related)) {
358 6
            unset($this->_related[$name]);
359
        } elseif ($this->getRelation($name, false) === null) {
360
            parent::__unset($name);
361
        }
362
    }
363
364
    /**
365
     * Declares a `has-one` relation.
366
     * The declaration is returned in terms of a relational [[ActiveQuery]] instance
367
     * through which the related record can be queried and retrieved back.
368
     *
369
     * A `has-one` relation means that there is at most one related record matching
370
     * the criteria set by this relation, e.g., a customer has one country.
371
     *
372
     * For example, to declare the `country` relation for `Customer` class, we can write
373
     * the following code in the `Customer` class:
374
     *
375
     * ```php
376
     * public function getCountry()
377
     * {
378
     *     return $this->hasOne(Country::class, ['id' => 'country_id']);
379
     * }
380
     * ```
381
     *
382
     * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
383
     * in the related class `Country`, while the 'country_id' value refers to an attribute name
384
     * in the current AR class.
385
     *
386
     * Call methods declared in [[ActiveQuery]] to further customize the relation.
387
     *
388
     * @param string $class the class name of the related record
389
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
390
     * the attributes of the record associated with the `$class` model, while the values of the
391
     * array refer to the corresponding attributes in **this** AR class.
392
     * @return ActiveQueryInterface the relational query object.
393
     */
394 109
    public function hasOne($class, $link)
395
    {
396 109
        return $this->createRelationQuery($class, $link, false);
397
    }
398
399
    /**
400
     * Declares a `has-many` relation.
401
     * The declaration is returned in terms of a relational [[ActiveQuery]] instance
402
     * through which the related record can be queried and retrieved back.
403
     *
404
     * A `has-many` relation means that there are multiple related records matching
405
     * the criteria set by this relation, e.g., a customer has many orders.
406
     *
407
     * For example, to declare the `orders` relation for `Customer` class, we can write
408
     * the following code in the `Customer` class:
409
     *
410
     * ```php
411
     * public function getOrders()
412
     * {
413
     *     return $this->hasMany(Order::class, ['customer_id' => 'id']);
414
     * }
415
     * ```
416
     *
417
     * Note that in the above, the 'customer_id' key in the `$link` parameter refers to
418
     * an attribute name in the related class `Order`, while the 'id' value refers to
419
     * an attribute name in the current AR class.
420
     *
421
     * Call methods declared in [[ActiveQuery]] to further customize the relation.
422
     *
423
     * @param string $class the class name of the related record
424
     * @param array $link the primary-foreign key constraint. The keys of the array refer to
425
     * the attributes of the record associated with the `$class` model, while the values of the
426
     * array refer to the corresponding attributes in **this** AR class.
427
     * @return ActiveQueryInterface the relational query object.
428
     */
429 183
    public function hasMany($class, $link)
430
    {
431 183
        return $this->createRelationQuery($class, $link, true);
432
    }
433
434
    /**
435
     * Creates a query instance for `has-one` or `has-many` relation.
436
     * @param string $class the class name of the related record.
437
     * @param array $link the primary-foreign key constraint.
438
     * @param bool $multiple whether this query represents a relation to more than one record.
439
     * @return ActiveQueryInterface the relational query object.
440
     * @since 2.0.12
441
     * @see hasOne()
442
     * @see hasMany()
443
     */
444 241
    protected function createRelationQuery($class, $link, $multiple)
445
    {
446
        /* @var $class ActiveRecordInterface */
447
        /* @var $query ActiveQuery */
448 241
        $query = $class::find();
449 241
        $query->primaryModel = $this;
450 241
        $query->link = $link;
451 241
        $query->multiple = $multiple;
452 241
        return $query;
453
    }
454
455
    /**
456
     * Populates the named relation with the related records.
457
     * Note that this method does not check if the relation exists or not.
458
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
459
     * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation.
460
     * @see getRelation()
461
     */
462 153
    public function populateRelation($name, $records)
463
    {
464 153
        foreach ($this->_relationsDependencies as &$relationNames) {
465 21
            unset($relationNames[$name]);
466
        }
467
468 153
        $this->_related[$name] = $records;
469
    }
470
471
    /**
472
     * Check whether the named relation has been populated with records.
473
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
474
     * @return bool whether relation has been populated with records.
475
     * @see getRelation()
476
     */
477 102
    public function isRelationPopulated($name)
478
    {
479 102
        return array_key_exists($name, $this->_related);
480
    }
481
482
    /**
483
     * Returns all populated related records.
484
     * @return array an array of related records indexed by relation names.
485
     * @see getRelation()
486
     */
487 6
    public function getRelatedRecords()
488
    {
489 6
        return $this->_related;
490
    }
491
492
    /**
493
     * Returns a value indicating whether the model has an attribute with the specified name.
494
     * @param string $name the name of the attribute
495
     * @return bool whether the model has an attribute with the specified name.
496
     */
497 375
    public function hasAttribute($name)
498
    {
499 375
        return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
500
    }
501
502
    /**
503
     * Returns the named attribute value.
504
     * If this record is the result of a query and the attribute is not loaded,
505
     * `null` will be returned.
506
     * @param string $name the attribute name
507
     * @return mixed the attribute value. `null` if the attribute is not set or does not exist.
508
     * @see hasAttribute()
509
     */
510 4
    public function getAttribute($name)
511
    {
512 4
        return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
513
    }
514
515
    /**
516
     * Sets the named attribute value.
517
     * @param string $name the attribute name
518
     * @param mixed $value the attribute value.
519
     * @throws InvalidArgumentException if the named attribute does not exist.
520
     * @see hasAttribute()
521
     */
522 107
    public function setAttribute($name, $value)
523
    {
524 107
        if ($this->hasAttribute($name)) {
525
            if (
526 107
                !empty($this->_relationsDependencies[$name])
527 107
                && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
528
            ) {
529 6
                $this->resetDependentRelations($name);
530
            }
531 107
            $this->_attributes[$name] = $value;
532
        } else {
533
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
534
        }
535
    }
536
537
    /**
538
     * Returns the old attribute values.
539
     * @return array the old attribute values (name-value pairs)
540
     */
541
    public function getOldAttributes()
542
    {
543
        return $this->_oldAttributes === null ? [] : $this->_oldAttributes;
544
    }
545
546
    /**
547
     * Sets the old attribute values.
548
     * All existing old attribute values will be discarded.
549
     * @param array|null $values old attribute values to be set.
550
     * If set to `null` this record is considered to be [[isNewRecord|new]].
551
     */
552 115
    public function setOldAttributes($values)
553
    {
554 115
        $this->_oldAttributes = $values;
555
    }
556
557
    /**
558
     * Returns the old value of the named attribute.
559
     * If this record is the result of a query and the attribute is not loaded,
560
     * `null` will be returned.
561
     * @param string $name the attribute name
562
     * @return mixed the old attribute value. `null` if the attribute is not loaded before
563
     * or does not exist.
564
     * @see hasAttribute()
565
     */
566
    public function getOldAttribute($name)
567
    {
568
        return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
569
    }
570
571
    /**
572
     * Sets the old value of the named attribute.
573
     * @param string $name the attribute name
574
     * @param mixed $value the old attribute value.
575
     * @throws InvalidArgumentException if the named attribute does not exist.
576
     * @see hasAttribute()
577
     */
578 123
    public function setOldAttribute($name, $value)
579
    {
580 123
        if ($this->canSetOldAttribute($name)) {
581 123
            $this->_oldAttributes[$name] = $value;
582
        } else {
583
            throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
584
        }
585
    }
586
587
    /**
588
     * Returns if the old named attribute can be set.
589
     * @param string $name the attribute name
590
     * @return bool whether the old attribute can be set
591
     * @see setOldAttribute()
592
     */
593 123
    public function canSetOldAttribute($name)
594
    {
595 123
        return (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name));
596
    }
597
598
    /**
599
     * Marks an attribute dirty.
600
     * This method may be called to force updating a record when calling [[update()]],
601
     * even if there is no change being made to the record.
602
     * @param string $name the attribute name
603
     */
604 7
    public function markAttributeDirty($name)
605
    {
606 7
        unset($this->_oldAttributes[$name]);
607
    }
608
609
    /**
610
     * Returns a value indicating whether the named attribute has been changed.
611
     * @param string $name the name of the attribute.
612
     * @param bool $identical whether the comparison of new and old value is made for
613
     * identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison.
614
     * This parameter is available since version 2.0.4.
615
     * @return bool whether the attribute has been changed
616
     */
617 2
    public function isAttributeChanged($name, $identical = true)
618
    {
619 2
        if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
620 1
            if ($identical) {
621 1
                return $this->_attributes[$name] !== $this->_oldAttributes[$name];
622
            }
623
624
            return $this->_attributes[$name] != $this->_oldAttributes[$name];
625
        }
626
627 1
        return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
628
    }
629
630
    /**
631
     * Returns the attribute values that have been modified since they are loaded or saved most recently.
632
     *
633
     * The comparison of new and old values is made for identical values using `===`.
634
     *
635
     * @param string[]|null $names the names of the attributes whose values may be returned if they are
636
     * changed recently. If null, [[attributes()]] will be used.
637
     * @return array the changed attribute values (name-value pairs)
638
     */
639 126
    public function getDirtyAttributes($names = null)
640
    {
641 126
        if ($names === null) {
642 123
            $names = $this->attributes();
643
        }
644 126
        $names = array_flip($names);
645 126
        $attributes = [];
646 126
        if ($this->_oldAttributes === null) {
647 112
            foreach ($this->_attributes as $name => $value) {
648 108
                if (isset($names[$name])) {
649 108
                    $attributes[$name] = $value;
650
                }
651
            }
652
        } else {
653 57
            foreach ($this->_attributes as $name => $value) {
654 57
                if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $this->isValueDifferent($value, $this->_oldAttributes[$name]))) {
655 53
                    $attributes[$name] = $value;
656
                }
657
            }
658
        }
659
660 126
        return $attributes;
661
    }
662
663
    /**
664
     * Saves the current record.
665
     *
666
     * This method will call [[insert()]] when [[isNewRecord]] is `true`, or [[update()]]
667
     * when [[isNewRecord]] is `false`.
668
     *
669
     * For example, to save a customer record:
670
     *
671
     * ```php
672
     * $customer = new Customer; // or $customer = Customer::findOne($id);
673
     * $customer->name = $name;
674
     * $customer->email = $email;
675
     * $customer->save();
676
     * ```
677
     *
678
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
679
     * before saving the record. Defaults to `true`. If the validation fails, the record
680
     * will not be saved to the database and this method will return `false`.
681
     * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
682
     * meaning all attributes that are loaded from DB will be saved.
683
     * @return bool whether the saving succeeded (i.e. no validation errors occurred).
684
     * @throws Exception in case update or insert failed.
685
     */
686 120
    public function save($runValidation = true, $attributeNames = null)
687
    {
688 120
        if ($this->getIsNewRecord()) {
689 106
            return $this->insert($runValidation, $attributeNames);
690
        }
691
692 31
        return $this->update($runValidation, $attributeNames) !== false;
693
    }
694
695
    /**
696
     * Saves the changes to this active record into the associated database table.
697
     *
698
     * This method performs the following steps in order:
699
     *
700
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
701
     *    returns `false`, the rest of the steps will be skipped;
702
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
703
     *    failed, the rest of the steps will be skipped;
704
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
705
     *    the rest of the steps will be skipped;
706
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
707
     * 5. call [[afterSave()]];
708
     *
709
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
710
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
711
     * will be raised by the corresponding methods.
712
     *
713
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
714
     *
715
     * For example, to update a customer record:
716
     *
717
     * ```php
718
     * $customer = Customer::findOne($id);
719
     * $customer->name = $name;
720
     * $customer->email = $email;
721
     * $customer->update();
722
     * ```
723
     *
724
     * Note that it is possible the update does not affect any row in the table.
725
     * In this case, this method will return 0. For this reason, you should use the following
726
     * code to check if update() is successful or not:
727
     *
728
     * ```php
729
     * if ($customer->update() !== false) {
730
     *     // update successful
731
     * } else {
732
     *     // update failed
733
     * }
734
     * ```
735
     *
736
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
737
     * before saving the record. Defaults to `true`. If the validation fails, the record
738
     * will not be saved to the database and this method will return `false`.
739
     * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
740
     * meaning all attributes that are loaded from DB will be saved.
741
     * @return int|false the number of rows affected, or `false` if validation fails
742
     * or [[beforeSave()]] stops the updating process.
743
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
744
     * being updated is outdated.
745
     * @throws Exception in case update failed.
746
     */
747
    public function update($runValidation = true, $attributeNames = null)
748
    {
749
        if ($runValidation && !$this->validate($attributeNames)) {
750
            return false;
751
        }
752
753
        return $this->updateInternal($attributeNames);
754
    }
755
756
    /**
757
     * Updates the specified attributes.
758
     *
759
     * This method is a shortcut to [[update()]] when data validation is not needed
760
     * and only a small set attributes need to be updated.
761
     *
762
     * You may specify the attributes to be updated as name list or name-value pairs.
763
     * If the latter, the corresponding attribute values will be modified accordingly.
764
     * The method will then save the specified attributes into database.
765
     *
766
     * Note that this method will **not** perform data validation and will **not** trigger events.
767
     *
768
     * @param array $attributes the attributes (names or name-value pairs) to be updated
769
     * @return int the number of rows affected.
770
     */
771 7
    public function updateAttributes($attributes)
772
    {
773 7
        $attrs = [];
774 7
        foreach ($attributes as $name => $value) {
775 7
            if (is_int($name)) {
776
                $attrs[] = $value;
777
            } else {
778 7
                $this->$name = $value;
779 7
                $attrs[] = $name;
780
            }
781
        }
782
783 7
        $values = $this->getDirtyAttributes($attrs);
784 7
        if (empty($values) || $this->getIsNewRecord()) {
785 4
            return 0;
786
        }
787
788 6
        $rows = static::updateAll($values, $this->getOldPrimaryKey(true));
789
790 6
        foreach ($values as $name => $value) {
791 6
            $this->_oldAttributes[$name] = $this->_attributes[$name];
792
        }
793
794 6
        return $rows;
795
    }
796
797
    /**
798
     * @see update()
799
     * @param array|null $attributes attributes to update
800
     * @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process.
801
     * @throws StaleObjectException
802
     */
803 41
    protected function updateInternal($attributes = null)
804
    {
805 41
        if (!$this->beforeSave(false)) {
806
            return false;
807
        }
808 41
        $values = $this->getDirtyAttributes($attributes);
809 41
        if (empty($values)) {
810 3
            $this->afterSave(false, $values);
811 3
            return 0;
812
        }
813 39
        $condition = $this->getOldPrimaryKey(true);
814 39
        $lock = $this->optimisticLock();
815 39
        if ($lock !== null) {
816 5
            $values[$lock] = $this->$lock + 1;
817 5
            $condition[$lock] = $this->$lock;
818
        }
819
        // We do not check the return value of updateAll() because it's possible
820
        // that the UPDATE statement doesn't change anything and thus returns 0.
821 39
        $rows = static::updateAll($values, $condition);
822
823 39
        if ($lock !== null && !$rows) {
824 4
            throw new StaleObjectException('The object being updated is outdated.');
825
        }
826
827 39
        if (isset($values[$lock])) {
828 5
            $this->$lock = $values[$lock];
829
        }
830
831 39
        $changedAttributes = [];
832 39
        foreach ($values as $name => $value) {
833 39
            $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
834 39
            $this->_oldAttributes[$name] = $value;
835
        }
836 39
        $this->afterSave(false, $changedAttributes);
837
838 39
        return $rows;
839
    }
840
841
    /**
842
     * Updates one or several counter columns for the current AR object.
843
     * Note that this method differs from [[updateAllCounters()]] in that it only
844
     * saves counters for the current AR object.
845
     *
846
     * An example usage is as follows:
847
     *
848
     * ```php
849
     * $post = Post::findOne($id);
850
     * $post->updateCounters(['view_count' => 1]);
851
     * ```
852
     *
853
     * @param array $counters the counters to be updated (attribute name => increment value)
854
     * Use negative values if you want to decrement the counters.
855
     * @return bool whether the saving is successful
856
     * @see updateAllCounters()
857
     */
858 6
    public function updateCounters($counters)
859
    {
860 6
        if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
861 6
            foreach ($counters as $name => $value) {
862 6
                if (!isset($this->_attributes[$name])) {
863 3
                    $this->_attributes[$name] = $value;
864
                } else {
865 3
                    $this->_attributes[$name] += $value;
866
                }
867 6
                $this->_oldAttributes[$name] = $this->_attributes[$name];
868
            }
869
870 6
            return true;
871
        }
872
873
        return false;
874
    }
875
876
    /**
877
     * Deletes the table row corresponding to this active record.
878
     *
879
     * This method performs the following steps in order:
880
     *
881
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
882
     *    rest of the steps;
883
     * 2. delete the record from the database;
884
     * 3. call [[afterDelete()]].
885
     *
886
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
887
     * will be raised by the corresponding methods.
888
     *
889
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
890
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
891
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
892
     * being deleted is outdated.
893
     * @throws Exception in case delete failed.
894
     */
895
    public function delete()
896
    {
897
        $result = false;
898
        if ($this->beforeDelete()) {
899
            // we do not check the return value of deleteAll() because it's possible
900
            // the record is already deleted in the database and thus the method will return 0
901
            $condition = $this->getOldPrimaryKey(true);
902
            $lock = $this->optimisticLock();
903
            if ($lock !== null) {
904
                $condition[$lock] = $this->$lock;
905
            }
906
            $result = static::deleteAll($condition);
907
            if ($lock !== null && !$result) {
908
                throw new StaleObjectException('The object being deleted is outdated.');
909
            }
910
            $this->_oldAttributes = null;
911
            $this->afterDelete();
912
        }
913
914
        return $result;
915
    }
916
917
    /**
918
     * Returns a value indicating whether the current record is new.
919
     * @return bool whether the record is new and should be inserted when calling [[save()]].
920
     */
921 169
    public function getIsNewRecord()
922
    {
923 169
        return $this->_oldAttributes === null;
924
    }
925
926
    /**
927
     * Sets the value indicating whether the record is new.
928
     * @param bool $value whether the record is new and should be inserted when calling [[save()]].
929
     * @see getIsNewRecord()
930
     */
931
    public function setIsNewRecord($value)
932
    {
933
        $this->_oldAttributes = $value ? null : $this->_attributes;
934
    }
935
936
    /**
937
     * Initializes the object.
938
     * This method is called at the end of the constructor.
939
     * The default implementation will trigger an [[EVENT_INIT]] event.
940
     */
941 583
    public function init()
942
    {
943 583
        parent::init();
944 583
        $this->trigger(self::EVENT_INIT);
945
    }
946
947
    /**
948
     * This method is called when the AR object is created and populated with the query result.
949
     * The default implementation will trigger an [[EVENT_AFTER_FIND]] event.
950
     * When overriding this method, make sure you call the parent implementation to ensure the
951
     * event is triggered.
952
     */
953 394
    public function afterFind()
954
    {
955 394
        $this->trigger(self::EVENT_AFTER_FIND);
956
    }
957
958
    /**
959
     * This method is called at the beginning of inserting or updating a record.
960
     *
961
     * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is `true`,
962
     * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is `false`.
963
     * When overriding this method, make sure you call the parent implementation like the following:
964
     *
965
     * ```php
966
     * public function beforeSave($insert)
967
     * {
968
     *     if (!parent::beforeSave($insert)) {
969
     *         return false;
970
     *     }
971
     *
972
     *     // ...custom code here...
973
     *     return true;
974
     * }
975
     * ```
976
     *
977
     * @param bool $insert whether this method called while inserting a record.
978
     * If `false`, it means the method is called while updating a record.
979
     * @return bool whether the insertion or updating should continue.
980
     * If `false`, the insertion or updating will be cancelled.
981
     */
982 132
    public function beforeSave($insert)
983
    {
984 132
        $event = new ModelEvent();
985 132
        $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
986
987 132
        return $event->isValid;
988
    }
989
990
    /**
991
     * This method is called at the end of inserting or updating a record.
992
     * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is `true`,
993
     * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]].
994
     * When overriding this method, make sure you call the parent implementation so that
995
     * the event is triggered.
996
     * @param bool $insert whether this method called while inserting a record.
997
     * If `false`, it means the method is called while updating a record.
998
     * @param array $changedAttributes The old values of attributes that had changed and were saved.
999
     * You can use this parameter to take action based on the changes made for example send an email
1000
     * when the password had changed or implement audit trail that tracks all the changes.
1001
     * `$changedAttributes` gives you the old attribute values while the active record (`$this`) has
1002
     * already the new, updated values.
1003
     *
1004
     * Note that no automatic type conversion performed by default. You may use
1005
     * [[\yii\behaviors\AttributeTypecastBehavior]] to facilitate attribute typecasting.
1006
     * See https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.
1007
     */
1008 123
    public function afterSave($insert, $changedAttributes)
1009
    {
1010 123
        $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
1011 123
            'changedAttributes' => $changedAttributes,
1012 123
        ]));
1013
    }
1014
1015
    /**
1016
     * This method is invoked before deleting a record.
1017
     *
1018
     * The default implementation raises the [[EVENT_BEFORE_DELETE]] event.
1019
     * When overriding this method, make sure you call the parent implementation like the following:
1020
     *
1021
     * ```php
1022
     * public function beforeDelete()
1023
     * {
1024
     *     if (!parent::beforeDelete()) {
1025
     *         return false;
1026
     *     }
1027
     *
1028
     *     // ...custom code here...
1029
     *     return true;
1030
     * }
1031
     * ```
1032
     *
1033
     * @return bool whether the record should be deleted. Defaults to `true`.
1034
     */
1035 7
    public function beforeDelete()
1036
    {
1037 7
        $event = new ModelEvent();
1038 7
        $this->trigger(self::EVENT_BEFORE_DELETE, $event);
1039
1040 7
        return $event->isValid;
1041
    }
1042
1043
    /**
1044
     * This method is invoked after deleting a record.
1045
     * The default implementation raises the [[EVENT_AFTER_DELETE]] event.
1046
     * You may override this method to do postprocessing after the record is deleted.
1047
     * Make sure you call the parent implementation so that the event is raised properly.
1048
     */
1049 7
    public function afterDelete()
1050
    {
1051 7
        $this->trigger(self::EVENT_AFTER_DELETE);
1052
    }
1053
1054
    /**
1055
     * Repopulates this active record with the latest data.
1056
     *
1057
     * If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered.
1058
     * This event is available since version 2.0.8.
1059
     *
1060
     * @return bool whether the row still exists in the database. If `true`, the latest data
1061
     * will be populated to this active record. Otherwise, this record will remain unchanged.
1062
     */
1063
    public function refresh()
1064
    {
1065
        /* @var $record BaseActiveRecord */
1066
        $record = static::findOne($this->getPrimaryKey(true));
1067
        return $this->refreshInternal($record);
1068
    }
1069
1070
    /**
1071
     * Repopulates this active record with the latest data from a newly fetched instance.
1072
     * @param BaseActiveRecord $record the record to take attributes from.
1073
     * @return bool whether refresh was successful.
1074
     * @see refresh()
1075
     * @since 2.0.13
1076
     */
1077 29
    protected function refreshInternal($record)
1078
    {
1079 29
        if ($record === null) {
1080 3
            return false;
1081
        }
1082 29
        foreach ($this->attributes() as $name) {
1083 29
            $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
1084
        }
1085 29
        $this->_oldAttributes = $record->_oldAttributes;
1086 29
        $this->_related = [];
1087 29
        $this->_relationsDependencies = [];
1088 29
        $this->afterRefresh();
1089
1090 29
        return true;
1091
    }
1092
1093
    /**
1094
     * This method is called when the AR object is refreshed.
1095
     * The default implementation will trigger an [[EVENT_AFTER_REFRESH]] event.
1096
     * When overriding this method, make sure you call the parent implementation to ensure the
1097
     * event is triggered.
1098
     * @since 2.0.8
1099
     */
1100 29
    public function afterRefresh()
1101
    {
1102 29
        $this->trigger(self::EVENT_AFTER_REFRESH);
1103
    }
1104
1105
    /**
1106
     * Returns a value indicating whether the given active record is the same as the current one.
1107
     * The comparison is made by comparing the table names and the primary key values of the two active records.
1108
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
1109
     * @param ActiveRecordInterface $record record to compare to
1110
     * @return bool whether the two active records refer to the same row in the same database table.
1111
     */
1112
    public function equals($record)
1113
    {
1114
        if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
1115
            return false;
1116
        }
1117
1118
        return get_class($this) === get_class($record) && $this->getPrimaryKey() === $record->getPrimaryKey();
1119
    }
1120
1121
    /**
1122
     * Returns the primary key value(s).
1123
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1124
     * the return value will be an array with column names as keys and column values as values.
1125
     * Note that for composite primary keys, an array will always be returned regardless of this parameter value.
1126
     * @return mixed the primary key value. An array (column name => column value) is returned if the primary key
1127
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1128
     * the key value is null).
1129
     */
1130 51
    public function getPrimaryKey($asArray = false)
1131
    {
1132 51
        $keys = static::primaryKey();
1133 51
        if (!$asArray && count($keys) === 1) {
1134 25
            return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
1135
        }
1136
1137 29
        $values = [];
1138 29
        foreach ($keys as $name) {
1139 29
            $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
1140
        }
1141
1142 29
        return $values;
1143
    }
1144
1145
    /**
1146
     * Returns the old primary key value(s).
1147
     * This refers to the primary key value that is populated into the record
1148
     * after executing a find method (e.g. find(), findOne()).
1149
     * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
1150
     * @param bool $asArray whether to return the primary key value as an array. If `true`,
1151
     * the return value will be an array with column name as key and column value as value.
1152
     * If this is `false` (default), a scalar value will be returned for non-composite primary key.
1153
     * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key
1154
     * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
1155
     * the key value is null).
1156
     * @throws Exception if the AR model does not have a primary key
1157
     */
1158 77
    public function getOldPrimaryKey($asArray = false)
1159
    {
1160 77
        $keys = static::primaryKey();
1161 77
        if (empty($keys)) {
1162
            throw new Exception(get_class($this) . ' does not have a primary key. You should either define a primary key for the corresponding table or override the primaryKey() method.');
1163
        }
1164 77
        if (!$asArray && count($keys) === 1) {
1165
            return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
1166
        }
1167
1168 77
        $values = [];
1169 77
        foreach ($keys as $name) {
1170 77
            $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
1171
        }
1172
1173 77
        return $values;
1174
    }
1175
1176
    /**
1177
     * Populates an active record object using a row of data from the database/storage.
1178
     *
1179
     * This is an internal method meant to be called to create active record objects after
1180
     * fetching data from the database. It is mainly used by [[ActiveQuery]] to populate
1181
     * the query results into active records.
1182
     *
1183
     * When calling this method manually you should call [[afterFind()]] on the created
1184
     * record to trigger the [[EVENT_AFTER_FIND|afterFind Event]].
1185
     *
1186
     * @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance
1187
     * created by [[instantiate()]] beforehand.
1188
     * @param array $row attribute values (name => value)
1189
     */
1190 394
    public static function populateRecord($record, $row)
1191
    {
1192 394
        $columns = array_flip($record->attributes());
1193 394
        foreach ($row as $name => $value) {
1194 394
            if (isset($columns[$name])) {
1195 394
                $record->_attributes[$name] = $value;
1196 6
            } elseif ($record->canSetProperty($name)) {
1197 6
                $record->$name = $value;
1198
            }
1199
        }
1200 394
        $record->_oldAttributes = $record->_attributes;
1201 394
        $record->_related = [];
1202 394
        $record->_relationsDependencies = [];
1203
    }
1204
1205
    /**
1206
     * Creates an active record instance.
1207
     *
1208
     * This method is called together with [[populateRecord()]] by [[ActiveQuery]].
1209
     * It is not meant to be used for creating new records directly.
1210
     *
1211
     * You may override this method if the instance being created
1212
     * depends on the row data to be populated into the record.
1213
     * For example, by creating a record based on the value of a column,
1214
     * you may implement the so-called single-table inheritance mapping.
1215
     * @param array $row row data to be populated into the record.
1216
     * @return static the newly created active record
1217
     */
1218 388
    public static function instantiate($row)
1219
    {
1220 388
        return new static();
1221
    }
1222
1223
    /**
1224
     * Returns whether there is an element at the specified offset.
1225
     * This method is required by the interface [[\ArrayAccess]].
1226
     * @param mixed $offset the offset to check on
1227
     * @return bool whether there is an element at the specified offset.
1228
     */
1229 239
    #[\ReturnTypeWillChange]
1230
    public function offsetExists($offset)
1231
    {
1232 239
        return $this->__isset($offset);
1233
    }
1234
1235
    /**
1236
     * Returns the relation object with the specified name.
1237
     * A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object.
1238
     * It can be declared in either the Active Record class itself or one of its behaviors.
1239
     * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
1240
     * @param bool $throwException whether to throw exception if the relation does not exist.
1241
     * @return ActiveQueryInterface|ActiveQuery|null the relational query object. If the relation does not exist
1242
     * and `$throwException` is `false`, `null` will be returned.
1243
     * @throws InvalidArgumentException if the named relation does not exist.
1244
     */
1245 210
    public function getRelation($name, $throwException = true)
1246
    {
1247 210
        $getter = 'get' . $name;
1248
        try {
1249
            // the relation could be defined in a behavior
1250 210
            $relation = $this->$getter();
1251 6
        } catch (UnknownMethodException $e) {
1252 6
            if ($throwException) {
1253 6
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
1254
            }
1255
1256
            return null;
1257
        }
1258 207
        if (!$relation instanceof ActiveQueryInterface) {
1259
            if ($throwException) {
1260
                throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".');
1261
            }
1262
1263
            return null;
1264
        }
1265
1266 207
        if (method_exists($this, $getter)) {
1267
            // relation name is case sensitive, trying to validate it when the relation is defined within this class
1268 207
            $method = new \ReflectionMethod($this, $getter);
1269 207
            $realName = lcfirst(substr($method->getName(), 3));
1270 207
            if ($realName !== $name) {
1271
                if ($throwException) {
1272
                    throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\".");
1273
                }
1274
1275
                return null;
1276
            }
1277
        }
1278
1279 207
        return $relation;
1280
    }
1281
1282
    /**
1283
     * Establishes the relationship between two models.
1284
     *
1285
     * The relationship is established by setting the foreign key value(s) in one model
1286
     * to be the corresponding primary key value(s) in the other model.
1287
     * The model with the foreign key will be saved into database **without** performing validation
1288
     * and **without** events/behaviors.
1289
     *
1290
     * If the relationship involves a junction table, a new row will be inserted into the
1291
     * junction table which contains the primary key values from both models.
1292
     *
1293
     * Note that this method requires that the primary key value is not null.
1294
     *
1295
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1296
     * @param ActiveRecordInterface $model the model to be linked with the current one.
1297
     * @param array $extraColumns additional column values to be saved into the junction table.
1298
     * This parameter is only meaningful for a relationship involving a junction table
1299
     * (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].)
1300
     * @throws InvalidCallException if the method is unable to link two models.
1301
     */
1302 9
    public function link($name, $model, $extraColumns = [])
1303
    {
1304
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1305 9
        $relation = $this->getRelation($name);
1306
1307 9
        if ($relation->via !== null) {
1308 3
            if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
1309
                throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
1310
            }
1311 3
            if (is_array($relation->via)) {
1312
                /* @var $viaRelation ActiveQuery */
1313 3
                list($viaName, $viaRelation) = $relation->via;
1314 3
                $viaClass = $viaRelation->modelClass;
1315
                // unset $viaName so that it can be reloaded to reflect the change
1316 3
                unset($this->_related[$viaName]);
1317
            } else {
1318
                $viaRelation = $relation->via;
1319
                $viaTable = reset($relation->via->from);
1320
            }
1321 3
            $columns = [];
1322 3
            foreach ($viaRelation->link as $a => $b) {
1323 3
                $columns[$a] = $this->$b;
1324
            }
1325 3
            foreach ($relation->link as $a => $b) {
1326 3
                $columns[$b] = $model->$a;
1327
            }
1328 3
            foreach ($extraColumns as $k => $v) {
1329 3
                $columns[$k] = $v;
1330
            }
1331 3
            if (is_array($relation->via)) {
1332
                /* @var $viaClass ActiveRecordInterface */
1333
                /* @var $record ActiveRecordInterface */
1334 3
                $record = Yii::createObject($viaClass);
1335 3
                foreach ($columns as $column => $value) {
1336 3
                    $record->$column = $value;
1337
                }
1338 3
                $record->insert(false);
1339
            } else {
1340
                /* @var $viaTable string */
1341 3
                static::getDb()->createCommand()->insert($viaTable, $columns)->execute();
1342
            }
1343
        } else {
1344 9
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1345 9
            $p2 = static::isPrimaryKey(array_values($relation->link));
1346 9
            if ($p1 && $p2) {
1347
                if ($this->getIsNewRecord()) {
1348
                    if ($model->getIsNewRecord()) {
1349
                        throw new InvalidCallException('Unable to link models: at most one model can be newly created.');
1350
                    }
1351
                    $this->bindModels(array_flip($relation->link), $this, $model);
1352
                } else {
1353
                    $this->bindModels($relation->link, $model, $this);
1354
                }
1355 9
            } elseif ($p1) {
1356 3
                $this->bindModels(array_flip($relation->link), $this, $model);
1357 9
            } elseif ($p2) {
1358 9
                $this->bindModels($relation->link, $model, $this);
1359
            } else {
1360
                throw new InvalidCallException('Unable to link models: the link defining the relation does not involve any primary key.');
1361
            }
1362
        }
1363
1364
        // update lazily loaded related objects
1365 9
        if (!$relation->multiple) {
1366 3
            $this->_related[$name] = $model;
1367 9
        } elseif (isset($this->_related[$name])) {
1368 9
            if ($relation->indexBy !== null) {
1369 6
                if ($relation->indexBy instanceof \Closure) {
1370 3
                    $index = call_user_func($relation->indexBy, $model);
1371
                } else {
1372 3
                    $index = $model->{$relation->indexBy};
1373
                }
1374 6
                $this->_related[$name][$index] = $model;
1375
            } else {
1376 3
                $this->_related[$name][] = $model;
1377
            }
1378
        }
1379
    }
1380
1381
    /**
1382
     * Destroys the relationship between two models.
1383
     *
1384
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1385
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1386
     *
1387
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1388
     * @param ActiveRecordInterface $model the model to be unlinked from the current one.
1389
     * You have to make sure that the model is really related with the current model as this method
1390
     * does not check this.
1391
     * @param bool $delete whether to delete the model that contains the foreign key.
1392
     * If `false`, the model's foreign key will be set `null` and saved.
1393
     * If `true`, the model containing the foreign key will be deleted.
1394
     * @throws InvalidCallException if the models cannot be unlinked
1395
     * @throws Exception
1396
     * @throws StaleObjectException
1397
     */
1398 9
    public function unlink($name, $model, $delete = false)
1399
    {
1400
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1401 9
        $relation = $this->getRelation($name);
1402
1403 9
        if ($relation->via !== null) {
1404 9
            if (is_array($relation->via)) {
1405
                /* @var $viaRelation ActiveQuery */
1406 9
                list($viaName, $viaRelation) = $relation->via;
1407 9
                $viaClass = $viaRelation->modelClass;
1408 9
                unset($this->_related[$viaName]);
1409
            } else {
1410 3
                $viaRelation = $relation->via;
1411 3
                $viaTable = reset($relation->via->from);
1412
            }
1413 9
            $columns = [];
1414 9
            foreach ($viaRelation->link as $a => $b) {
1415 9
                $columns[$a] = $this->$b;
1416
            }
1417 9
            foreach ($relation->link as $a => $b) {
1418 9
                $columns[$b] = $model->$a;
1419
            }
1420 9
            $nulls = [];
1421 9
            foreach (array_keys($columns) as $a) {
1422 9
                $nulls[$a] = null;
1423
            }
1424 9
            if (property_exists($viaRelation, 'on') && $viaRelation->on !== null) {
1425 6
                $columns = ['and', $columns, $viaRelation->on];
1426
            }
1427 9
            if (is_array($relation->via)) {
1428
                /* @var $viaClass ActiveRecordInterface */
1429 9
                if ($delete) {
1430 6
                    $viaClass::deleteAll($columns);
1431
                } else {
1432 9
                    $viaClass::updateAll($nulls, $columns);
1433
                }
1434
            } else {
1435
                /* @var $viaTable string */
1436
                /* @var $command Command */
1437 3
                $command = static::getDb()->createCommand();
1438 3
                if ($delete) {
1439
                    $command->delete($viaTable, $columns)->execute();
1440
                } else {
1441 9
                    $command->update($viaTable, $nulls, $columns)->execute();
1442
                }
1443
            }
1444
        } else {
1445 3
            $p1 = $model->isPrimaryKey(array_keys($relation->link));
1446 3
            $p2 = static::isPrimaryKey(array_values($relation->link));
1447 3
            if ($p2) {
1448 3
                if ($delete) {
1449 3
                    $model->delete();
1450
                } else {
1451 3
                    foreach ($relation->link as $a => $b) {
1452 3
                        $model->$a = null;
1453
                    }
1454 3
                    $model->save(false);
1455
                }
1456
            } elseif ($p1) {
1457
                foreach ($relation->link as $a => $b) {
1458
                    if (is_array($this->$b)) { // relation via array valued attribute
1459
                        if (($key = array_search($model->$a, $this->$b, false)) !== false) {
1460
                            $values = $this->$b;
1461
                            unset($values[$key]);
1462
                            $this->$b = array_values($values);
1463
                        }
1464
                    } else {
1465
                        $this->$b = null;
1466
                    }
1467
                }
1468
                $delete ? $this->delete() : $this->save(false);
1469
            } else {
1470
                throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
1471
            }
1472
        }
1473
1474 9
        if (!$relation->multiple) {
1475
            unset($this->_related[$name]);
1476 9
        } elseif (isset($this->_related[$name])) {
1477
            /* @var $b ActiveRecordInterface */
1478 9
            foreach ($this->_related[$name] as $a => $b) {
1479 9
                if ($model->getPrimaryKey() === $b->getPrimaryKey()) {
1480 9
                    unset($this->_related[$name][$a]);
1481
                }
1482
            }
1483
        }
1484
    }
1485
1486
    /**
1487
     * Destroys the relationship in current model.
1488
     *
1489
     * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
1490
     * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
1491
     *
1492
     * Note that to destroy the relationship without removing records make sure your keys can be set to null
1493
     *
1494
     * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
1495
     * @param bool $delete whether to delete the model that contains the foreign key.
1496
     *
1497
     * Note that the deletion will be performed using [[deleteAll()]], which will not trigger any events on the related models.
1498
     * If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first
1499
     * and then call [[delete()]] on each of them.
1500
     */
1501 18
    public function unlinkAll($name, $delete = false)
1502
    {
1503
        /* @var $relation ActiveQueryInterface|ActiveQuery */
1504 18
        $relation = $this->getRelation($name);
1505
1506 18
        if ($relation->via !== null) {
1507 9
            if (is_array($relation->via)) {
1508
                /* @var $viaRelation ActiveQuery */
1509 6
                list($viaName, $viaRelation) = $relation->via;
1510 6
                $viaClass = $viaRelation->modelClass;
1511 6
                unset($this->_related[$viaName]);
1512
            } else {
1513 3
                $viaRelation = $relation->via;
1514 3
                $viaTable = reset($relation->via->from);
1515
            }
1516 9
            $condition = [];
1517 9
            $nulls = [];
1518 9
            foreach ($viaRelation->link as $a => $b) {
1519 9
                $nulls[$a] = null;
1520 9
                $condition[$a] = $this->$b;
1521
            }
1522 9
            if (!empty($viaRelation->where)) {
1523
                $condition = ['and', $condition, $viaRelation->where];
1524
            }
1525 9
            if (property_exists($viaRelation, 'on') && !empty($viaRelation->on)) {
1526
                $condition = ['and', $condition, $viaRelation->on];
1527
            }
1528 9
            if (is_array($relation->via)) {
1529
                /* @var $viaClass ActiveRecordInterface */
1530 6
                if ($delete) {
1531 6
                    $viaClass::deleteAll($condition);
1532
                } else {
1533 6
                    $viaClass::updateAll($nulls, $condition);
1534
                }
1535
            } else {
1536
                /* @var $viaTable string */
1537
                /* @var $command Command */
1538 3
                $command = static::getDb()->createCommand();
1539 3
                if ($delete) {
1540 3
                    $command->delete($viaTable, $condition)->execute();
1541
                } else {
1542 9
                    $command->update($viaTable, $nulls, $condition)->execute();
1543
                }
1544
            }
1545
        } else {
1546
            /* @var $relatedModel ActiveRecordInterface */
1547 12
            $relatedModel = $relation->modelClass;
1548 12
            if (!$delete && count($relation->link) === 1 && is_array($this->{$b = reset($relation->link)})) {
0 ignored issues
show
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1549
                // relation via array valued attribute
1550
                $this->$b = [];
1551
                $this->save(false);
1552
            } else {
1553 12
                $nulls = [];
1554 12
                $condition = [];
1555 12
                foreach ($relation->link as $a => $b) {
1556 12
                    $nulls[$a] = null;
1557 12
                    $condition[$a] = $this->$b;
1558
                }
1559 12
                if (!empty($relation->where)) {
1560 6
                    $condition = ['and', $condition, $relation->where];
1561
                }
1562 12
                if (property_exists($relation, 'on') && !empty($relation->on)) {
1563 3
                    $condition = ['and', $condition, $relation->on];
1564
                }
1565 12
                if ($delete) {
1566 9
                    $relatedModel::deleteAll($condition);
1567
                } else {
1568 6
                    $relatedModel::updateAll($nulls, $condition);
1569
                }
1570
            }
1571
        }
1572
1573 18
        unset($this->_related[$name]);
1574
    }
1575
1576
    /**
1577
     * @param array $link
1578
     * @param ActiveRecordInterface $foreignModel
1579
     * @param ActiveRecordInterface $primaryModel
1580
     * @throws InvalidCallException
1581
     */
1582 9
    private function bindModels($link, $foreignModel, $primaryModel)
1583
    {
1584 9
        foreach ($link as $fk => $pk) {
1585 9
            $value = $primaryModel->$pk;
1586 9
            if ($value === null) {
1587
                throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.');
1588
            }
1589 9
            if (is_array($foreignModel->$fk)) { // relation via array valued attribute
1590
                $foreignModel->{$fk}[] = $value;
1591
            } else {
1592 9
                $foreignModel->{$fk} = $value;
1593
            }
1594
        }
1595 9
        $foreignModel->save(false);
1596
    }
1597
1598
    /**
1599
     * Returns a value indicating whether the given set of attributes represents the primary key for this model.
1600
     * @param array $keys the set of attributes to check
1601
     * @return bool whether the given set of attributes represents the primary key for this model
1602
     */
1603 15
    public static function isPrimaryKey($keys)
1604
    {
1605 15
        $pks = static::primaryKey();
1606 15
        if (count($keys) === count($pks)) {
1607 15
            return count(array_intersect($keys, $pks)) === count($pks);
1608
        }
1609
1610 9
        return false;
1611
    }
1612
1613
    /**
1614
     * Returns the text label for the specified attribute.
1615
     * The attribute may be specified in a dot format to retrieve the label from related model or allow this model to override the label defined in related model.
1616
     * For example, if the attribute is specified as 'relatedModel1.relatedModel2.attr' the function will return the first label definition it can find
1617
     * in the following order:
1618
     * - the label for 'relatedModel1.relatedModel2.attr' defined in [[attributeLabels()]] of this model;
1619
     * - the label for 'relatedModel2.attr' defined in related model represented by relation 'relatedModel1' of this model;
1620
     * - the label for 'attr' defined in related model represented by relation 'relatedModel2' of relation 'relatedModel1'.
1621
     *   If no label definition was found then the value of $this->generateAttributeLabel('relatedModel1.relatedModel2.attr') will be returned.
1622
     * @param string $attribute the attribute name
1623
     * @return string the attribute label
1624
     * @see attributeLabels()
1625
     * @see generateAttributeLabel()
1626
     */
1627 58
    public function getAttributeLabel($attribute)
1628
    {
1629 58
        $model = $this;
1630 58
        $modelAttribute = $attribute;
1631
        for (;;) {
1632 58
            $labels = $model->attributeLabels();
1633 58
            if (isset($labels[$modelAttribute])) {
1634 11
                return $labels[$modelAttribute];
1635
            }
1636
1637 54
            $parts = explode('.', $modelAttribute, 2);
1638 54
            if (count($parts) < 2) {
1639 48
                break;
1640
            }
1641
1642 6
            list ($relationName, $modelAttribute) = $parts;
1643
1644 6
            if ($model->isRelationPopulated($relationName) && $model->$relationName instanceof self) {
1645 3
                $model = $model->$relationName;
1646
            } else {
1647
                try {
1648 6
                    $relation = $model->getRelation($relationName);
1649 6
                } catch (InvalidArgumentException $e) {
1650 6
                    break;
1651
                }
1652
                /* @var $modelClass ActiveRecordInterface */
1653 3
                $modelClass = $relation->modelClass;
1654 58
                $model = $modelClass::instance();
1655
            }
1656
        }
1657
1658 54
        return $this->generateAttributeLabel($attribute);
1659
    }
1660
1661
    /**
1662
     * Returns the text hint for the specified attribute.
1663
     * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
1664
     * @param string $attribute the attribute name
1665
     * @return string the attribute hint
1666
     * @see attributeHints()
1667
     * @since 2.0.4
1668
     */
1669
    public function getAttributeHint($attribute)
1670
    {
1671
        $hints = $this->attributeHints();
1672
        if (isset($hints[$attribute])) {
1673
            return $hints[$attribute];
1674
        } elseif (strpos($attribute, '.')) {
1675
            $attributeParts = explode('.', $attribute);
1676
            $neededAttribute = array_pop($attributeParts);
1677
1678
            $relatedModel = $this;
1679
            foreach ($attributeParts as $relationName) {
1680
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
1681
                    $relatedModel = $relatedModel->$relationName;
1682
                } else {
1683
                    try {
1684
                        $relation = $relatedModel->getRelation($relationName);
1685
                    } catch (InvalidParamException $e) {
1686
                        return '';
1687
                    }
1688
                    /* @var $modelClass ActiveRecordInterface */
1689
                    $modelClass = $relation->modelClass;
1690
                    $relatedModel = $modelClass::instance();
1691
                }
1692
            }
1693
1694
            $hints = $relatedModel->attributeHints();
1695
            if (isset($hints[$neededAttribute])) {
1696
                return $hints[$neededAttribute];
1697
            }
1698
        }
1699
1700
        return '';
1701
    }
1702
1703
    /**
1704
     * {@inheritdoc}
1705
     *
1706
     * The default implementation returns the names of the columns whose values have been populated into this record.
1707
     */
1708 3
    public function fields()
1709
    {
1710 3
        $fields = array_keys($this->_attributes);
1711
1712 3
        return array_combine($fields, $fields);
1713
    }
1714
1715
    /**
1716
     * {@inheritdoc}
1717
     *
1718
     * The default implementation returns the names of the relations that have been populated into this record.
1719
     */
1720
    public function extraFields()
1721
    {
1722
        $fields = array_keys($this->getRelatedRecords());
1723
1724
        return array_combine($fields, $fields);
1725
    }
1726
1727
    /**
1728
     * Sets the element value at the specified offset to null.
1729
     * This method is required by the SPL interface [[\ArrayAccess]].
1730
     * It is implicitly called when you use something like `unset($model[$offset])`.
1731
     * @param mixed $offset the offset to unset element
1732
     */
1733 3
    public function offsetUnset($offset)
1734
    {
1735 3
        if (property_exists($this, $offset)) {
1736
            $this->$offset = null;
1737
        } else {
1738 3
            unset($this->$offset);
1739
        }
1740
    }
1741
1742
    /**
1743
     * Resets dependent related models checking if their links contain specific attribute.
1744
     * @param string $attribute The changed attribute name.
1745
     */
1746 15
    private function resetDependentRelations($attribute)
1747
    {
1748 15
        foreach ($this->_relationsDependencies[$attribute] as $relation) {
1749 15
            unset($this->_related[$relation]);
1750
        }
1751 15
        unset($this->_relationsDependencies[$attribute]);
1752
    }
1753
1754
    /**
1755
     * Sets relation dependencies for a property
1756
     * @param string $name property name
1757
     * @param ActiveQueryInterface $relation relation instance
1758
     * @param string|null $viaRelationName intermediate relation
1759
     */
1760 88
    private function setRelationDependencies($name, $relation, $viaRelationName = null)
1761
    {
1762 88
        if (empty($relation->via) && $relation->link) {
1763 85
            foreach ($relation->link as $attribute) {
1764 85
                $this->_relationsDependencies[$attribute][$name] = $name;
1765 85
                if ($viaRelationName !== null) {
1766 36
                    $this->_relationsDependencies[$attribute][] = $viaRelationName;
1767
                }
1768
            }
1769 51
        } elseif ($relation->via instanceof ActiveQueryInterface) {
1770 15
            $this->setRelationDependencies($name, $relation->via);
1771 39
        } elseif (is_array($relation->via)) {
1772 36
            list($viaRelationName, $viaQuery) = $relation->via;
1773 36
            $this->setRelationDependencies($name, $viaQuery, $viaRelationName);
1774
        }
1775
    }
1776
1777
    /**
1778
     * @param mixed $newValue
1779
     * @param mixed $oldValue
1780
     * @return bool
1781
     * @since 2.0.48
1782
     */
1783 57
    private function isValueDifferent($newValue, $oldValue)
1784
    {
1785 57
        if (is_array($newValue) && is_array($oldValue) && ArrayHelper::isAssociative($oldValue)) {
1786 7
            $newValue = ArrayHelper::recursiveSort($newValue);
1787 7
            $oldValue = ArrayHelper::recursiveSort($oldValue);
1788
        }
1789
1790 57
        return $newValue !== $oldValue;
1791
    }
1792
1793
    /**
1794
     * Eager loads related models for the already loaded primary models.
1795
     *
1796
     * Helps to reduce the number of queries performed against database if some related models are only used
1797
     * when a specific condition is met. For example:
1798
     *
1799
     * ```php
1800
     * $customers = Customer::find()->where(['country_id' => 123])->all();
1801
     * if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
1802
     *     Customer::loadRelationsFor($customers, 'orders.items');
1803
     * }
1804
     * ```
1805
     *
1806
     * @param array|ActiveRecordInterface[] $models array of primary models. Each model should have the same type and can be:
1807
     * - an active record instance;
1808
     * - active record instance represented by array (i.e. active record was loaded using [[ActiveQuery::asArray()]]).
1809
     * @param string|array $relationNames the names of the relations of primary models to be loaded from database. See [[ActiveQueryInterface::with()]] on how to specify this argument.
1810
     * @param bool $asArray whether to load each related model as an array or an object (if the relation itself does not specify that).
1811
     * @since 2.0.50
1812
     */
1813 3
    public static function loadRelationsFor(&$models, $relationNames, $asArray = false)
1814
    {
1815
        // ActiveQueryTrait::findWith() called below assumes $models array is non-empty.
1816 3
        if (empty($models)) {
1817
            return;
1818
        }
1819
1820 3
        static::find()->asArray($asArray)->findWith((array)$relationNames, $models);
1821
    }
1822
1823
    /**
1824
     * Eager loads related models for the already loaded primary model.
1825
     *
1826
     * Helps to reduce the number of queries performed against database if some related models are only used
1827
     * when a specific condition is met. For example:
1828
     *
1829
     * ```php
1830
     * $customer = Customer::find()->where(['id' => 123])->one();
1831
     * if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
1832
     *     $customer->loadRelations('orders.items');
1833
     * }
1834
     * ```
1835
     *
1836
     * @param string|array $relationNames the names of the relations of this model to be loaded from database. See [[ActiveQueryInterface::with()]] on how to specify this argument.
1837
     * @param bool $asArray whether to load each relation as an array or an object (if the relation itself does not specify that).
1838
     * @since 2.0.50
1839
     */
1840 3
    public function loadRelations($relationNames, $asArray = false)
1841
    {
1842 3
        $models = [$this];
1843 3
        static::loadRelationsFor($models, $relationNames, $asArray);
1844
    }
1845
}
1846