ActiveRecord.php 21.1 KB
Newer Older
w  
Qiang Xue committed
1 2 3 4
<?php
/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
Qiang Xue committed
5
 * @copyright Copyright (c) 2008 Yii Software LLC
w  
Qiang Xue committed
6 7 8
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
9
namespace yii\db;
w  
Qiang Xue committed
10

Qiang Xue committed
11
use yii\base\InvalidConfigException;
12
use yii\helpers\Inflector;
13
use yii\helpers\StringHelper;
w  
Qiang Xue committed
14

w  
Qiang Xue committed
15
/**
Qiang Xue committed
16
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
w  
Qiang Xue committed
17
 *
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
 * Active Record implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record).
 * The premise behind Active Record is that an individual [[ActiveRecord]] object is associated with a specific
 * row in a database table. The object's attributes are mapped to the columns of the corresponding table.
 * Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.
 *
 * As an example, say that the `Customer` ActiveRecord class is associated with the `tbl_customer` table.
 * This would mean that the class's `name` attribute is automatically mapped to the `name` column in `tbl_customer`.
 * Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of
 * the `name` column for the table row, you can use the expression `$customer->name`.
 * In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
 * But Active Record provides much more functionality than this.
 *
 * To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and
 * implement the `tableName` method:
 *
 * ```php
 * <?php
 *
 * class Customer extends \yii\db\ActiveRecord
 * {
 *     /**
 *      * @return string the name of the table associated with this ActiveRecord class.
 *      * /
 *     public static function tableName()
 *     {
 *         return 'tbl_customer';
 *     }
 * }
 * ```
 *
 * The `tableName` method only has to return the name of the database table associated with the class.
 *
 * > Tip: You may also use the [Gii code generator][guide-gii] to generate ActiveRecord classes from your
 * > database tables.
 *
 * Class instances are obtained in one of two ways:
 *
 * * Using the `new` operator to create a new, empty object
 * * Using a method to fetch an existing record (or records) from the database
 *
 * Here is a short teaser how working with an ActiveRecord looks like:
 *
 * ```php
 * $user = new User();
 * $user->name = 'Qiang';
 * $user->save();  // a new row is inserted into tbl_user
 *
 * // the following will retrieve the user 'CeBe' from the database
 * $user = User::find()->where(['name' => 'CeBe'])->one();
 *
 * // this will get related records from table tbl_orders when relation is defined
 * $orders = $user->orders;
 * ```
 *
 * For more details and usage information on ActiveRecord, see the [guide article on ActiveRecord][guide-active-record].
w  
Qiang Xue committed
73
 *
Qiang Xue committed
74
 * @author Qiang Xue <qiang.xue@gmail.com>
75
 * @author Carsten Brandt <mail@cebe.cc>
Qiang Xue committed
76
 * @since 2.0
w  
Qiang Xue committed
77
 */
78
class ActiveRecord extends BaseActiveRecord
w  
Qiang Xue committed
79
{
80
	/**
81
	 * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
82
	 */
83
	const OP_INSERT = 0x01;
84
	/**
85
	 * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
86
	 */
87
	const OP_UPDATE = 0x02;
88
	/**
89
	 * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
90
	 */
91 92 93 94 95 96
	const OP_DELETE = 0x04;
	/**
	 * All three operations: insert, update, delete.
	 * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE.
	 */
	const OP_ALL = 0x07;
97

Qiang Xue committed
98 99 100 101 102 103
	/**
	 * Returns the database connection used by this AR class.
	 * By default, the "db" application component is used as the database connection.
	 * You may override this method if you want to use a different database connection.
	 * @return Connection the database connection used by this AR class.
	 */
Qiang Xue committed
104
	public static function getDb()
Qiang Xue committed
105
	{
Qiang Xue committed
106
		return \Yii::$app->getDb();
Qiang Xue committed
107 108
	}

Qiang Xue committed
109
	/**
Qiang Xue committed
110 111 112 113 114 115 116 117 118 119 120 121 122
	 * Creates an [[ActiveQuery]] instance with a given SQL statement.
	 *
	 * Note that because the SQL statement is already specified, calling additional
	 * query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]]
	 * instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
	 * still fine.
	 *
	 * Below is an example:
	 *
	 * ~~~
	 * $customers = Customer::findBySql('SELECT * FROM tbl_customer')->all();
	 * ~~~
	 *
Qiang Xue committed
123 124
	 * @param string $sql the SQL statement to be executed
	 * @param array $params parameters to be bound to the SQL statement during execution.
Qiang Xue committed
125
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance
Qiang Xue committed
126
	 */
Alexander Makarov committed
127
	public static function findBySql($sql, $params = [])
w  
Qiang Xue committed
128
	{
Qiang Xue committed
129
		$query = static::createQuery();
Qiang Xue committed
130 131 132 133 134 135
		$query->sql = $sql;
		return $query->params($params);
	}

	/**
	 * Updates the whole table using the provided attribute values and conditions.
Qiang Xue committed
136 137 138
	 * For example, to change the status to be 1 for all customers whose status is 2:
	 *
	 * ~~~
Alexander Makarov committed
139
	 * Customer::updateAll(['status' => 1], 'status = 2');
Qiang Xue committed
140 141 142 143
	 * ~~~
	 *
	 * @param array $attributes attribute values (name-value pairs) to be saved into the table
	 * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
Qiang Xue committed
144
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
145
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
146 147
	 * @return integer the number of rows updated
	 */
Alexander Makarov committed
148
	public static function updateAll($attributes, $condition = '', $params = [])
w  
Qiang Xue committed
149
	{
Qiang Xue committed
150
		$command = static::getDb()->createCommand();
Qiang Xue committed
151 152
		$command->update(static::tableName(), $attributes, $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
153 154
	}

Qiang Xue committed
155
	/**
Qiang Xue committed
156 157 158 159
	 * Updates the whole table using the provided counter changes and conditions.
	 * For example, to increment all customers' age by 1,
	 *
	 * ~~~
Alexander Makarov committed
160
	 * Customer::updateAllCounters(['age' => 1]);
Qiang Xue committed
161 162
	 * ~~~
	 *
Qiang Xue committed
163
	 * @param array $counters the counters to be updated (attribute name => increment value).
Qiang Xue committed
164 165
	 * Use negative values if you want to decrement the counters.
	 * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
Qiang Xue committed
166
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
167
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
168
	 * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
Qiang Xue committed
169 170
	 * @return integer the number of rows updated
	 */
Alexander Makarov committed
171
	public static function updateAllCounters($counters, $condition = '', $params = [])
w  
Qiang Xue committed
172
	{
Qiang Xue committed
173
		$n = 0;
Qiang Xue committed
174
		foreach ($counters as $name => $value) {
Alexander Makarov committed
175
			$counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
Qiang Xue committed
176
			$n++;
Qiang Xue committed
177
		}
178
		$command = static::getDb()->createCommand();
Qiang Xue committed
179 180
		$command->update(static::tableName(), $counters, $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
181 182
	}

Qiang Xue committed
183 184
	/**
	 * Deletes rows in the table using the provided conditions.
Qiang Xue committed
185 186 187 188 189 190 191 192 193
	 * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
	 *
	 * For example, to delete all customers whose status is 3:
	 *
	 * ~~~
	 * Customer::deleteAll('status = 3');
	 * ~~~
	 *
	 * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
Qiang Xue committed
194
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
195
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
196
	 * @return integer the number of rows deleted
Qiang Xue committed
197
	 */
Alexander Makarov committed
198
	public static function deleteAll($condition = '', $params = [])
w  
Qiang Xue committed
199
	{
Qiang Xue committed
200
		$command = static::getDb()->createCommand();
Qiang Xue committed
201 202
		$command->delete(static::tableName(), $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
203 204
	}

.  
Qiang Xue committed
205
	/**
Qiang Xue committed
206
	 * Creates an [[ActiveQuery]] instance.
207
	 *
208 209
	 * This method is called by [[find()]], [[findBySql()]] to start a SELECT query but also
	 * by [[hasOne()]] and [[hasMany()]] to create a relational query.
Qiang Xue committed
210 211
	 * You may override this method to return a customized query (e.g. `CustomerQuery` specified
	 * written for querying `Customer` purpose.)
212 213 214 215
	 *
	 * You may also define default conditions that should apply to all queries unless overridden:
	 *
	 * ```php
216
	 * public static function createQuery($config = [])
217
	 * {
218
	 *     return parent::createQuery($config)->where(['deleted' => false]);
219 220 221 222 223 224
	 * }
	 * ```
	 *
	 * Note that all queries should use [[Query::andWhere()]] and [[Query::orWhere()]] to keep the
	 * default condition. Using [[Query::where()]] will override the default condition.
	 *
225
	 * @param array $config the configuration passed to the ActiveQuery class.
Qiang Xue committed
226
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance.
.  
Qiang Xue committed
227
	 */
228
	public static function createQuery($config = [])
w  
Qiang Xue committed
229
	{
230 231
		$config['modelClass'] = get_called_class();
		return new ActiveQuery($config);
w  
Qiang Xue committed
232 233 234
	}

	/**
Qiang Xue committed
235
	 * Declares the name of the database table associated with this AR class.
236
	 * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
237
	 * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is 'tbl_',
238 239
	 * 'Customer' becomes 'tbl_customer', and 'OrderItem' becomes 'tbl_order_item'. You may override this method
	 * if the table is not named after this convention.
w  
Qiang Xue committed
240 241
	 * @return string the table name
	 */
Qiang Xue committed
242
	public static function tableName()
w  
Qiang Xue committed
243
	{
244
		return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
w  
Qiang Xue committed
245 246 247
	}

	/**
Qiang Xue committed
248 249
	 * Returns the schema information of the DB table associated with this AR class.
	 * @return TableSchema the schema information of the DB table associated with this AR class.
250
	 * @throws InvalidConfigException if the table for the AR class does not exist.
w  
Qiang Xue committed
251
	 */
Qiang Xue committed
252
	public static function getTableSchema()
w  
Qiang Xue committed
253
	{
254 255 256 257 258 259
		$schema = static::getDb()->getTableSchema(static::tableName());
		if ($schema !== null) {
			return $schema;
		} else {
			throw new InvalidConfigException("The table does not exist: " . static::tableName());
		}
w  
Qiang Xue committed
260 261 262
	}

	/**
Qiang Xue committed
263 264
	 * Returns the primary key name(s) for this AR class.
	 * The default implementation will return the primary key(s) as declared
Qiang Xue committed
265
	 * in the DB table that is associated with this AR class.
Qiang Xue committed
266
	 *
Qiang Xue committed
267 268 269
	 * If the DB table does not declare any primary key, you should override
	 * this method to return the attributes that you want to use as primary keys
	 * for this AR class.
Qiang Xue committed
270 271 272
	 *
	 * Note that an array should be returned even for a table with single primary key.
	 *
Qiang Xue committed
273
	 * @return string[] the primary keys of the associated database table.
w  
Qiang Xue committed
274
	 */
Qiang Xue committed
275
	public static function primaryKey()
w  
Qiang Xue committed
276
	{
Qiang Xue committed
277
		return static::getTableSchema()->primaryKey;
w  
Qiang Xue committed
278 279
	}

280
	/**
281 282 283
	 * Returns the list of all attribute names of the model.
	 * The default implementation will return all column names of the table associated with this AR class.
	 * @return array list of attribute names.
284
	 */
285
	public function attributes()
286
	{
287
		return array_keys(static::getTableSchema()->columns);
288 289
	}

290 291 292 293 294 295 296 297 298 299 300
	/**
	 * Declares which DB operations should be performed within a transaction in different scenarios.
	 * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
	 * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
	 * By default, these methods are NOT enclosed in a DB transaction.
	 *
	 * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
	 * in transactions. You can do so by overriding this method and returning the operations
	 * that need to be transactional. For example,
	 *
	 * ~~~
Alexander Makarov committed
301
	 * return [
302 303 304 305 306
	 *     'admin' => self::OP_INSERT,
	 *     'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
	 *     // the above is equivalent to the following:
	 *     // 'api' => self::OP_ALL,
	 *
Alexander Makarov committed
307
	 * ];
308 309 310 311 312 313 314 315 316 317 318
	 * ~~~
	 *
	 * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
	 * should be done in a transaction; and in the "api" scenario, all the operations should be done
	 * in a transaction.
	 *
	 * @return array the declarations of transactional operations. The array keys are scenarios names,
	 * and the array values are the corresponding transaction operations.
	 */
	public function transactions()
	{
Alexander Makarov committed
319
		return [];
320 321
	}

Vladimir Zbrailov committed
322
	/**
323
	 * @inheritdoc
Vladimir Zbrailov committed
324
	 */
325
	public static function populateRecord($record, $row)
Vladimir Zbrailov committed
326
	{
327
		$columns = static::getTableSchema()->columns;
Vladimir Zbrailov committed
328 329
		foreach ($row as $name => $value) {
			if (isset($columns[$name])) {
330
				$row[$name] = $columns[$name]->typecast($value);
Vladimir Zbrailov committed
331 332
			}
		}
333
		parent::populateRecord($record, $row);
Vladimir Zbrailov committed
334 335
	}

Qiang Xue committed
336
	/**
Qiang Xue committed
337 338 339 340 341 342
	 * Inserts a row into the associated database table using the attribute values of this record.
	 *
	 * This method performs the following steps in order:
	 *
	 * 1. call [[beforeValidate()]] when `$runValidation` is true. If validation
	 *    fails, it will skip the rest of the steps;
343 344
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
Qiang Xue committed
345
	 *    rest of the steps;
346 347
	 * 4. insert the record into database. If this fails, it will skip the rest of the steps;
	 * 5. call [[afterSave()]];
Qiang Xue committed
348
	 *
349
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
Qiang Xue committed
350 351
	 * [[EVENT_BEFORE_INSERT]], [[EVENT_AFTER_INSERT]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
Qiang Xue committed
352
	 *
353
	 * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
Qiang Xue committed
354 355
	 *
	 * If the table's primary key is auto-incremental and is null during insertion,
Qiang Xue committed
356
	 * it will be populated with the actual value after insertion.
Qiang Xue committed
357 358 359 360 361 362 363 364 365 366 367 368
	 *
	 * For example, to insert a customer record:
	 *
	 * ~~~
	 * $customer = new Customer;
	 * $customer->name = $name;
	 * $customer->email = $email;
	 * $customer->insert();
	 * ~~~
	 *
	 * @param boolean $runValidation whether to perform validation before saving the record.
	 * If the validation fails, the record will not be inserted into the database.
Qiang Xue committed
369 370 371
	 * @param array $attributes list of attributes that need to be saved. Defaults to null,
	 * meaning all attributes that are loaded from DB will be saved.
	 * @return boolean whether the attributes are valid and the record is inserted successfully.
372
	 * @throws \Exception in case insert failed.
Qiang Xue committed
373
	 */
Qiang Xue committed
374
	public function insert($runValidation = true, $attributes = null)
Qiang Xue committed
375
	{
376 377 378 379
		if ($runValidation && !$this->validate($attributes)) {
			return false;
		}
		$db = static::getDb();
Qiang Xue committed
380 381 382 383
		if ($this->isTransactional(self::OP_INSERT) && $db->getTransaction() === null) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->insertInternal($attributes);
resurtm committed
384
				if ($result === false) {
385
					$transaction->rollBack();
386 387 388
				} else {
					$transaction->commit();
				}
Qiang Xue committed
389
			} catch (\Exception $e) {
390
				$transaction->rollBack();
Qiang Xue committed
391
				throw $e;
392
			}
Qiang Xue committed
393 394
		} else {
			$result = $this->insertInternal($attributes);
395 396 397 398 399 400 401
		}
		return $result;
	}

	/**
	 * @see ActiveRecord::insert()
	 */
resurtm committed
402
	private function insertInternal($attributes = null)
403 404
	{
		if (!$this->beforeSave(true)) {
Qiang Xue committed
405 406
			return false;
		}
407 408
		$values = $this->getDirtyAttributes($attributes);
		if (empty($values)) {
409 410
			foreach ($this->getPrimaryKey(true) as $key => $value) {
				$values[$key] = $value;
Qiang Xue committed
411
			}
412 413 414
		}
		$db = static::getDb();
		$command = $db->createCommand()->insert($this->tableName(), $values);
415 416 417 418 419 420
		if (!$command->execute()) {
			return false;
		}
		$table = $this->getTableSchema();
		if ($table->sequenceName !== null) {
			foreach ($table->primaryKey as $name) {
421 422 423 424
				if ($this->getAttribute($name) === null) {
					$id = $db->getLastInsertID($table->sequenceName);
					$this->setAttribute($name, $id);
					$this->setOldAttribute($name, $id);
425
					break;
Qiang Xue committed
426 427 428
				}
			}
		}
429
		foreach ($values as $name => $value) {
430
			$this->setOldAttribute($name, $value);
431 432 433
		}
		$this->afterSave(true);
		return true;
Qiang Xue committed
434 435 436
	}

	/**
Qiang Xue committed
437 438 439 440 441 442
	 * Saves the changes to this active record into the associated database table.
	 *
	 * This method performs the following steps in order:
	 *
	 * 1. call [[beforeValidate()]] when `$runValidation` is true. If validation
	 *    fails, it will skip the rest of the steps;
443 444
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
Qiang Xue committed
445
	 *    rest of the steps;
446 447
	 * 4. save the record into database. If this fails, it will skip the rest of the steps;
	 * 5. call [[afterSave()]];
Qiang Xue committed
448
	 *
449
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
Qiang Xue committed
450 451
	 * [[EVENT_BEFORE_UPDATE]], [[EVENT_AFTER_UPDATE]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
Qiang Xue committed
452
	 *
453
	 * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
Qiang Xue committed
454 455 456 457 458 459 460 461 462 463
	 *
	 * For example, to update a customer record:
	 *
	 * ~~~
	 * $customer = Customer::find($id);
	 * $customer->name = $name;
	 * $customer->email = $email;
	 * $customer->update();
	 * ~~~
	 *
464 465 466 467 468 469 470 471 472 473 474 475
	 * Note that it is possible the update does not affect any row in the table.
	 * In this case, this method will return 0. For this reason, you should use the following
	 * code to check if update() is successful or not:
	 *
	 * ~~~
	 * if ($this->update() !== false) {
	 *     // update successful
	 * } else {
	 *     // update failed
	 * }
	 * ~~~
	 *
Qiang Xue committed
476 477
	 * @param boolean $runValidation whether to perform validation before saving the record.
	 * If the validation fails, the record will not be inserted into the database.
Qiang Xue committed
478 479
	 * @param array $attributes list of attributes that need to be saved. Defaults to null,
	 * meaning all attributes that are loaded from DB will be saved.
480 481
	 * @return integer|boolean the number of rows affected, or false if validation fails
	 * or [[beforeSave()]] stops the updating process.
482
	 * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
483
	 * being updated is outdated.
484
	 * @throws \Exception in case update failed.
Qiang Xue committed
485
	 */
Qiang Xue committed
486
	public function update($runValidation = true, $attributes = null)
Qiang Xue committed
487
	{
488
		if ($runValidation && !$this->validate($attributes)) {
Qiang Xue committed
489 490
			return false;
		}
491
		$db = static::getDb();
Qiang Xue committed
492 493 494 495
		if ($this->isTransactional(self::OP_UPDATE) && $db->getTransaction() === null) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->updateInternal($attributes);
resurtm committed
496
				if ($result === false) {
497
					$transaction->rollBack();
498 499
				} else {
					$transaction->commit();
500
				}
Qiang Xue committed
501
			} catch (\Exception $e) {
502
				$transaction->rollBack();
Qiang Xue committed
503
				throw $e;
504
			}
Qiang Xue committed
505 506
		} else {
			$result = $this->updateInternal($attributes);
507 508 509
		}
		return $result;
	}
510

Qiang Xue committed
511
	/**
Qiang Xue committed
512 513 514 515 516 517 518 519 520
	 * Deletes the table row corresponding to this active record.
	 *
	 * This method performs the following steps in order:
	 *
	 * 1. call [[beforeDelete()]]. If the method returns false, it will skip the
	 *    rest of the steps;
	 * 2. delete the record from the database;
	 * 3. call [[afterDelete()]].
	 *
Qiang Xue committed
521
	 * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
Qiang Xue committed
522 523
	 * will be raised by the corresponding methods.
	 *
524 525
	 * @return integer|boolean the number of rows deleted, or false if the deletion is unsuccessful for some reason.
	 * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
526
	 * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
527
	 * being deleted is outdated.
528
	 * @throws \Exception in case delete failed.
Qiang Xue committed
529 530 531
	 */
	public function delete()
	{
532
		$db = static::getDb();
533
		$transaction = $this->isTransactional(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
534 535 536 537 538 539 540
		try {
			$result = false;
			if ($this->beforeDelete()) {
				// we do not check the return value of deleteAll() because it's possible
				// the record is already deleted in the database and thus the method will return 0
				$condition = $this->getOldPrimaryKey(true);
				$lock = $this->optimisticLock();
resurtm committed
541
				if ($lock !== null) {
542 543 544
					$condition[$lock] = $this->$lock;
				}
				$result = $this->deleteAll($condition);
resurtm committed
545
				if ($lock !== null && !$result) {
546 547
					throw new StaleObjectException('The object being deleted is outdated.');
				}
548
				$this->setOldAttributes(null);
549
				$this->afterDelete();
550
			}
resurtm committed
551 552
			if ($transaction !== null) {
				if ($result === false) {
553
					$transaction->rollBack();
554 555 556
				} else {
					$transaction->commit();
				}
557
			}
558
		} catch (\Exception $e) {
resurtm committed
559
			if ($transaction !== null) {
560
				$transaction->rollBack();
561 562
			}
			throw $e;
Qiang Xue committed
563
		}
564
		return $result;
w  
Qiang Xue committed
565 566 567
	}

	/**
Qiang Xue committed
568 569
	 * Returns a value indicating whether the given active record is the same as the current one.
	 * The comparison is made by comparing the table names and the primary key values of the two active records.
570
	 * If one of the records [[isNewRecord|is new]] they are also considered not equal.
Qiang Xue committed
571
	 * @param ActiveRecord $record record to compare to
Qiang Xue committed
572
	 * @return boolean whether the two active records refer to the same row in the same database table.
w  
Qiang Xue committed
573
	 */
Qiang Xue committed
574
	public function equals($record)
w  
Qiang Xue committed
575
	{
576 577 578
		if ($this->isNewRecord || $record->isNewRecord) {
			return false;
		}
Qiang Xue committed
579
		return $this->tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
w  
Qiang Xue committed
580 581
	}

582
	/**
583 584 585
	 * Returns a value indicating whether the specified operation is transactional in the current [[scenario]].
	 * @param integer $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
	 * @return boolean whether the specified operation is transactional in the current [[scenario]].
586
	 */
587
	public function isTransactional($operation)
588 589
	{
		$scenario = $this->getScenario();
590 591
		$transactions = $this->transactions();
		return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
592
	}
w  
Qiang Xue committed
593
}