Completed
Push — fix-numbervalidator-comma-deci... ( 08054b...a7f0a3 )
by Alexander
40:41 queued 37:41
created

ActiveRecord::findByCondition()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.246

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 20
ccs 11
cts 14
cp 0.7856
rs 8.8571
cc 5
eloc 12
nc 4
nop 1
crap 5.246
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\db;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Inflector;
14
use yii\helpers\StringHelper;
15
16
/**
17
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
18
 *
19
 * Active Record implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record).
20
 * The premise behind Active Record is that an individual [[ActiveRecord]] object is associated with a specific
21
 * row in a database table. The object's attributes are mapped to the columns of the corresponding table.
22
 * Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.
23
 *
24
 * As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table.
25
 * This would mean that the class's `name` attribute is automatically mapped to the `name` column in `customer` table.
26
 * Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of
27
 * the `name` column for the table row, you can use the expression `$customer->name`.
28
 * In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
29
 * But Active Record provides much more functionality than this.
30
 *
31
 * To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and
32
 * implement the `tableName` method:
33
 *
34
 * ```php
35
 * <?php
36
 *
37
 * class Customer extends \yii\db\ActiveRecord
38
 * {
39
 *     public static function tableName()
40
 *     {
41
 *         return 'customer';
42
 *     }
43
 * }
44
 * ```
45
 *
46
 * The `tableName` method only has to return the name of the database table associated with the class.
47
 *
48
 * > Tip: You may also use the [Gii code generator](guide:start-gii) to generate ActiveRecord classes from your
49
 * > database tables.
50
 *
51
 * Class instances are obtained in one of two ways:
52
 *
53
 * * Using the `new` operator to create a new, empty object
54
 * * Using a method to fetch an existing record (or records) from the database
55
 *
56
 * Below is an example showing some typical usage of ActiveRecord:
57
 *
58
 * ```php
59
 * $user = new User();
60
 * $user->name = 'Qiang';
61
 * $user->save();  // a new row is inserted into user table
62
 *
63
 * // the following will retrieve the user 'CeBe' from the database
64
 * $user = User::find()->where(['name' => 'CeBe'])->one();
65
 *
66
 * // this will get related records from orders table when relation is defined
67
 * $orders = $user->orders;
68
 * ```
69
 *
70
 * For more details and usage information on ActiveRecord, see the [guide article on ActiveRecord](guide:db-active-record).
71
 *
72
 * @method ActiveQuery hasMany($class, array $link) see [[BaseActiveRecord::hasMany()]] for more info
73
 * @method ActiveQuery hasOne($class, array $link) see [[BaseActiveRecord::hasOne()]] for more info
74
 *
75
 * @author Qiang Xue <[email protected]>
76
 * @author Carsten Brandt <[email protected]>
77
 * @since 2.0
78
 */
79
class ActiveRecord extends BaseActiveRecord
80
{
81
    /**
82
     * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
83
     */
84
    const OP_INSERT = 0x01;
85
    /**
86
     * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
87
     */
88
    const OP_UPDATE = 0x02;
89
    /**
90
     * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
91
     */
92
    const OP_DELETE = 0x04;
93
    /**
94
     * All three operations: insert, update, delete.
95
     * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE.
96
     */
97
    const OP_ALL = 0x07;
98
99
100
    /**
101
     * Loads default values from database table schema
102
     *
103
     * You may call this method to load default values after creating a new instance:
104
     *
105
     * ```php
106
     * // class Customer extends \yii\db\ActiveRecord
107
     * $customer = new Customer();
108
     * $customer->loadDefaultValues();
109
     * ```
110
     *
111
     * @param bool $skipIfSet whether existing value should be preserved.
112
     * This will only set defaults for attributes that are `null`.
113
     * @return $this the model instance itself.
114
     */
115 4
    public function loadDefaultValues($skipIfSet = true)
116
    {
117 4
        foreach (static::getTableSchema()->columns as $column) {
118 4
            if ($column->defaultValue !== null && (!$skipIfSet || $this->{$column->name} === null)) {
119 4
                $this->{$column->name} = $column->defaultValue;
120 4
            }
121 4
        }
122 4
        return $this;
123
    }
124
125
    /**
126
     * Returns the database connection used by this AR class.
127
     * By default, the "db" application component is used as the database connection.
128
     * You may override this method if you want to use a different database connection.
129
     * @return Connection the database connection used by this AR class.
130
     */
131 19
    public static function getDb()
132
    {
133 19
        return Yii::$app->getDb();
134
    }
135
136
    /**
137
     * Creates an [[ActiveQuery]] instance with a given SQL statement.
138
     *
139
     * Note that because the SQL statement is already specified, calling additional
140
     * query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]]
141
     * instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
142
     * still fine.
143
     *
144
     * Below is an example:
145
     *
146
     * ```php
147
     * $customers = Customer::findBySql('SELECT * FROM customer')->all();
148
     * ```
149
     *
150
     * @param string $sql the SQL statement to be executed
151
     * @param array $params parameters to be bound to the SQL statement during execution.
152
     * @return ActiveQuery the newly created [[ActiveQuery]] instance
153
     */
154 6
    public static function findBySql($sql, $params = [])
155
    {
156 6
        $query = static::find();
157 6
        $query->sql = $sql;
158
159 6
        return $query->params($params);
160
    }
161
162
    /**
163
     * Finds ActiveRecord instance(s) by the given condition.
164
     * This method is internally called by [[findOne()]] and [[findAll()]].
165
     * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
166
     * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
167
     * @throws InvalidConfigException if there is no primary key defined
168
     * @internal
169
     */
170 161
    protected static function findByCondition($condition)
171
    {
172 161
        $query = static::find();
173
174 161
        if (!ArrayHelper::isAssociative($condition)) {
175
            // query by primary key
176 136
            $primaryKey = static::primaryKey();
177 136
            if (isset($primaryKey[0])) {
178 136
                $pk = $primaryKey[0];
179 136
                if (!empty($query->join) || !empty($query->joinWith)) {
180
                    $pk = static::tableName() . '.' . $pk;
181
                }
182 136
                $condition = [$pk => $condition];
183 136
            } else {
184
                throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
185
            }
186 136
        }
187
188 161
        return $query->andWhere($condition);
189
    }
190
191
    /**
192
     * Updates the whole table using the provided attribute values and conditions.
193
     * For example, to change the status to be 1 for all customers whose status is 2:
194
     *
195
     * ```php
196
     * Customer::updateAll(['status' => 1], 'status = 2');
197
     * ```
198
     *
199
     * @param array $attributes attribute values (name-value pairs) to be saved into the table
200
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
201
     * Please refer to [[Query::where()]] on how to specify this parameter.
202
     * @param array $params the parameters (name => value) to be bound to the query.
203
     * @return int the number of rows updated
204
     */
205 35
    public static function updateAll($attributes, $condition = '', $params = [])
206
    {
207 35
        $command = static::getDb()->createCommand();
208 35
        $command->update(static::tableName(), $attributes, $condition, $params);
209
210 35
        return $command->execute();
211
    }
212
213
    /**
214
     * Updates the whole table using the provided counter changes and conditions.
215
     * For example, to increment all customers' age by 1,
216
     *
217
     * ```php
218
     * Customer::updateAllCounters(['age' => 1]);
219
     * ```
220
     *
221
     * @param array $counters the counters to be updated (attribute name => increment value).
222
     * Use negative values if you want to decrement the counters.
223
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
224
     * Please refer to [[Query::where()]] on how to specify this parameter.
225
     * @param array $params the parameters (name => value) to be bound to the query.
226
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
227
     * @return int the number of rows updated
228
     */
229 6
    public static function updateAllCounters($counters, $condition = '', $params = [])
230
    {
231 6
        $n = 0;
232 6
        foreach ($counters as $name => $value) {
233 6
            $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
234 6
            $n++;
235 6
        }
236 6
        $command = static::getDb()->createCommand();
237 6
        $command->update(static::tableName(), $counters, $condition, $params);
238
239 6
        return $command->execute();
240
    }
241
242
    /**
243
     * Deletes rows in the table using the provided conditions.
244
     * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
245
     *
246
     * For example, to delete all customers whose status is 3:
247
     *
248
     * ```php
249
     * Customer::deleteAll('status = 3');
250
     * ```
251
     *
252
     * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
253
     * Please refer to [[Query::where()]] on how to specify this parameter.
254
     * @param array $params the parameters (name => value) to be bound to the query.
255
     * @return int the number of rows deleted
256
     */
257 31
    public static function deleteAll($condition = '', $params = [])
258
    {
259 31
        $command = static::getDb()->createCommand();
260 31
        $command->delete(static::tableName(), $condition, $params);
261
262 31
        return $command->execute();
263
    }
264
265
    /**
266
     * @inheritdoc
267
     * @return ActiveQuery the newly created [[ActiveQuery]] instance.
268
     */
269 229
    public static function find()
270
    {
271 229
        return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
272
    }
273
274
    /**
275
     * Declares the name of the database table associated with this AR class.
276
     * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
277
     * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
278
     * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
279
     * if the table is not named after this convention.
280
     * @return string the table name
281
     */
282 6
    public static function tableName()
283
    {
284 6
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
285
    }
286
287
    /**
288
     * Returns the schema information of the DB table associated with this AR class.
289
     * @return TableSchema the schema information of the DB table associated with this AR class.
290
     * @throws InvalidConfigException if the table for the AR class does not exist.
291
     */
292 298
    public static function getTableSchema()
293
    {
294 298
        $tableSchema = static::getDb()
295 298
            ->getSchema()
296 298
            ->getTableSchema(static::tableName());
297
298 298
        if ($tableSchema === null) {
299
            throw new InvalidConfigException('The table does not exist: ' . static::tableName());
300
        }
301
302 298
        return $tableSchema;
303
    }
304
305
    /**
306
     * Returns the primary key name(s) for this AR class.
307
     * The default implementation will return the primary key(s) as declared
308
     * in the DB table that is associated with this AR class.
309
     *
310
     * If the DB table does not declare any primary key, you should override
311
     * this method to return the attributes that you want to use as primary keys
312
     * for this AR class.
313
     *
314
     * Note that an array should be returned even for a table with single primary key.
315
     *
316
     * @return string[] the primary keys of the associated database table.
317
     */
318 187
    public static function primaryKey()
319
    {
320 187
        return static::getTableSchema()->primaryKey;
321
    }
322
323
    /**
324
     * Returns the list of all attribute names of the model.
325
     * The default implementation will return all column names of the table associated with this AR class.
326
     * @return array list of attribute names.
327
     */
328 295
    public function attributes()
329
    {
330 295
        return array_keys(static::getTableSchema()->columns);
331
    }
332
333
    /**
334
     * Declares which DB operations should be performed within a transaction in different scenarios.
335
     * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
336
     * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
337
     * By default, these methods are NOT enclosed in a DB transaction.
338
     *
339
     * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
340
     * in transactions. You can do so by overriding this method and returning the operations
341
     * that need to be transactional. For example,
342
     *
343
     * ```php
344
     * return [
345
     *     'admin' => self::OP_INSERT,
346
     *     'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
347
     *     // the above is equivalent to the following:
348
     *     // 'api' => self::OP_ALL,
349
     *
350
     * ];
351
     * ```
352
     *
353
     * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
354
     * should be done in a transaction; and in the "api" scenario, all the operations should be done
355
     * in a transaction.
356
     *
357
     * @return array the declarations of transactional operations. The array keys are scenarios names,
358
     * and the array values are the corresponding transaction operations.
359
     */
360 86
    public function transactions()
361
    {
362 86
        return [];
363
    }
364
365
    /**
366
     * @inheritdoc
367
     */
368 253
    public static function populateRecord($record, $row)
369
    {
370 253
        $columns = static::getTableSchema()->columns;
371 253
        foreach ($row as $name => $value) {
372 253
            if (isset($columns[$name])) {
373 253
                $row[$name] = $columns[$name]->phpTypecast($value);
374 253
            }
375 253
        }
376 253
        parent::populateRecord($record, $row);
377 253
    }
378
379
    /**
380
     * Inserts a row into the associated database table using the attribute values of this record.
381
     *
382
     * This method performs the following steps in order:
383
     *
384
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
385
     *    returns `false`, the rest of the steps will be skipped;
386
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
387
     *    failed, the rest of the steps will be skipped;
388
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
389
     *    the rest of the steps will be skipped;
390
     * 4. insert the record into database. If this fails, it will skip the rest of the steps;
391
     * 5. call [[afterSave()]];
392
     *
393
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
394
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
395
     * will be raised by the corresponding methods.
396
     *
397
     * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
398
     *
399
     * If the table's primary key is auto-incremental and is `null` during insertion,
400
     * it will be populated with the actual value after insertion.
401
     *
402
     * For example, to insert a customer record:
403
     *
404
     * ```php
405
     * $customer = new Customer;
406
     * $customer->name = $name;
407
     * $customer->email = $email;
408
     * $customer->insert();
409
     * ```
410
     *
411
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
412
     * before saving the record. Defaults to `true`. If the validation fails, the record
413
     * will not be saved to the database and this method will return `false`.
414
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
415
     * meaning all attributes that are loaded from DB will be saved.
416
     * @return bool whether the attributes are valid and the record is inserted successfully.
417
     * @throws \Exception in case insert failed.
418
     */
419 70
    public function insert($runValidation = true, $attributes = null)
420
    {
421 70
        if ($runValidation && !$this->validate($attributes)) {
422
            Yii::info('Model not inserted due to validation error.', __METHOD__);
423
            return false;
424
        }
425
426 70
        if (!$this->isTransactional(self::OP_INSERT)) {
427 70
            return $this->insertInternal($attributes);
428
        }
429
430
        $transaction = static::getDb()->beginTransaction();
431
        try {
432
            $result = $this->insertInternal($attributes);
433
            if ($result === false) {
434
                $transaction->rollBack();
435
            } else {
436
                $transaction->commit();
437
            }
438
            return $result;
439
        } catch (\Exception $e) {
440
            $transaction->rollBack();
441
            throw $e;
442
        }
443
    }
444
445
    /**
446
     * Inserts an ActiveRecord into DB without considering transaction.
447
     * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
448
     * meaning all attributes that are loaded from DB will be saved.
449
     * @return bool whether the record is inserted successfully.
450
     */
451 70
    protected function insertInternal($attributes = null)
452
    {
453 70
        if (!$this->beforeSave(true)) {
454
            return false;
455
        }
456 70
        $values = $this->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 451 can also be of type array; however, yii\db\BaseActiveRecord::getDirtyAttributes() does only seem to accept array<integer,string>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
457 70
        if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
458
            return false;
459
        }
460 70
        foreach ($primaryKeys as $name => $value) {
461 60
            $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
462 60
            $this->setAttribute($name, $id);
463 60
            $values[$name] = $id;
464 70
        }
465
466 70
        $changedAttributes = array_fill_keys(array_keys($values), null);
467 70
        $this->setOldAttributes($values);
468 70
        $this->afterSave(true, $changedAttributes);
469
470 70
        return true;
471
    }
472
473
    /**
474
     * Saves the changes to this active record into the associated database table.
475
     *
476
     * This method performs the following steps in order:
477
     *
478
     * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
479
     *    returns `false`, the rest of the steps will be skipped;
480
     * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
481
     *    failed, the rest of the steps will be skipped;
482
     * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
483
     *    the rest of the steps will be skipped;
484
     * 4. save the record into database. If this fails, it will skip the rest of the steps;
485
     * 5. call [[afterSave()]];
486
     *
487
     * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
488
     * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
489
     * will be raised by the corresponding methods.
490
     *
491
     * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
492
     *
493
     * For example, to update a customer record:
494
     *
495
     * ```php
496
     * $customer = Customer::findOne($id);
497
     * $customer->name = $name;
498
     * $customer->email = $email;
499
     * $customer->update();
500
     * ```
501
     *
502
     * Note that it is possible the update does not affect any row in the table.
503
     * In this case, this method will return 0. For this reason, you should use the following
504
     * code to check if update() is successful or not:
505
     *
506
     * ```php
507
     * if ($customer->update() !== false) {
508
     *     // update successful
509
     * } else {
510
     *     // update failed
511
     * }
512
     * ```
513
     *
514
     * @param bool $runValidation whether to perform validation (calling [[validate()]])
515
     * before saving the record. Defaults to `true`. If the validation fails, the record
516
     * will not be saved to the database and this method will return `false`.
517
     * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
518
     * meaning all attributes that are loaded from DB will be saved.
519
     * @return int|false the number of rows affected, or false if validation fails
520
     * or [[beforeSave()]] stops the updating process.
521
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
522
     * being updated is outdated.
523
     * @throws \Exception in case update failed.
524
     */
525 25
    public function update($runValidation = true, $attributeNames = null)
526
    {
527 25
        if ($runValidation && !$this->validate($attributeNames)) {
528
            Yii::info('Model not updated due to validation error.', __METHOD__);
529
            return false;
530
        }
531
532 25
        if (!$this->isTransactional(self::OP_UPDATE)) {
533 25
            return $this->updateInternal($attributeNames);
534
        }
535
536
        $transaction = static::getDb()->beginTransaction();
537
        try {
538
            $result = $this->updateInternal($attributeNames);
539
            if ($result === false) {
540
                $transaction->rollBack();
541
            } else {
542
                $transaction->commit();
543
            }
544
            return $result;
545
        } catch (\Exception $e) {
546
            $transaction->rollBack();
547
            throw $e;
548
        }
549
    }
550
551
    /**
552
     * Deletes the table row corresponding to this active record.
553
     *
554
     * This method performs the following steps in order:
555
     *
556
     * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
557
     *    rest of the steps;
558
     * 2. delete the record from the database;
559
     * 3. call [[afterDelete()]].
560
     *
561
     * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
562
     * will be raised by the corresponding methods.
563
     *
564
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
565
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
566
     * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
567
     * being deleted is outdated.
568
     * @throws \Exception in case delete failed.
569
     */
570 6
    public function delete()
571
    {
572 6
        if (!$this->isTransactional(self::OP_DELETE)) {
573 6
            return $this->deleteInternal();
574
        }
575
576
        $transaction = static::getDb()->beginTransaction();
577
        try {
578
            $result = $this->deleteInternal();
579
            if ($result === false) {
580
                $transaction->rollBack();
581
            } else {
582
                $transaction->commit();
583
            }
584
            return $result;
585
        } catch (\Exception $e) {
586
            $transaction->rollBack();
587
            throw $e;
588
        }
589
    }
590
591
    /**
592
     * Deletes an ActiveRecord without considering transaction.
593
     * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
594
     * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
595
     * @throws StaleObjectException
596
     */
597 6
    protected function deleteInternal()
598
    {
599 6
        if (!$this->beforeDelete()) {
600
            return false;
601
        }
602
603
        // we do not check the return value of deleteAll() because it's possible
604
        // the record is already deleted in the database and thus the method will return 0
605 6
        $condition = $this->getOldPrimaryKey(true);
606 6
        $lock = $this->optimisticLock();
607 6
        if ($lock !== null) {
608
            $condition[$lock] = $this->$lock;
609
        }
610 6
        $result = static::deleteAll($condition);
611 6
        if ($lock !== null && !$result) {
612
            throw new StaleObjectException('The object being deleted is outdated.');
613
        }
614 6
        $this->setOldAttributes(null);
615 6
        $this->afterDelete();
616
617 6
        return $result;
618
    }
619
620
    /**
621
     * Returns a value indicating whether the given active record is the same as the current one.
622
     * The comparison is made by comparing the table names and the primary key values of the two active records.
623
     * If one of the records [[isNewRecord|is new]] they are also considered not equal.
624
     * @param ActiveRecord $record record to compare to
625
     * @return bool whether the two active records refer to the same row in the same database table.
626
     */
627 3
    public function equals($record)
628
    {
629 3
        if ($this->isNewRecord || $record->isNewRecord) {
630 3
            return false;
631
        }
632
633 3
        return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
634
    }
635
636
    /**
637
     * Returns a value indicating whether the specified operation is transactional in the current [[scenario]].
638
     * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
639
     * @return bool whether the specified operation is transactional in the current [[scenario]].
640
     */
641 86
    public function isTransactional($operation)
642
    {
643 86
        $scenario = $this->getScenario();
644 86
        $transactions = $this->transactions();
645
646 86
        return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
647
    }
648
}
649