ActiveRecord.php 21.6 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
 * 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
 * {
 *     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
70
 *
Qiang Xue committed
71
 * @author Qiang Xue <qiang.xue@gmail.com>
72
 * @author Carsten Brandt <mail@cebe.cc>
Qiang Xue committed
73
 * @since 2.0
w  
Qiang Xue committed
74
 */
75
class ActiveRecord extends BaseActiveRecord
w  
Qiang Xue committed
76
{
77
	/**
78
	 * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
79
	 */
80
	const OP_INSERT = 0x01;
81
	/**
82
	 * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
83
	 */
84
	const OP_UPDATE = 0x02;
85
	/**
86
	 * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
87
	 */
88 89 90 91 92 93
	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;
94

Qiang Xue committed
95 96 97 98 99 100
	/**
	 * 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
101
	public static function getDb()
Qiang Xue committed
102
	{
Qiang Xue committed
103
		return \Yii::$app->getDb();
Qiang Xue committed
104 105
	}

Qiang Xue committed
106
	/**
Qiang Xue committed
107 108 109 110 111 112 113 114 115 116 117 118 119
	 * 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
120 121
	 * @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
122
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance
Qiang Xue committed
123
	 */
Alexander Makarov committed
124
	public static function findBySql($sql, $params = [])
w  
Qiang Xue committed
125
	{
Qiang Xue committed
126
		$query = static::createQuery();
Qiang Xue committed
127 128 129 130 131 132
		$query->sql = $sql;
		return $query->params($params);
	}

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

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

Qiang Xue committed
180 181
	/**
	 * Deletes rows in the table using the provided conditions.
Qiang Xue committed
182 183 184 185 186 187 188 189 190
	 * 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
191
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
192
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
193
	 * @return integer the number of rows deleted
Qiang Xue committed
194
	 */
Alexander Makarov committed
195
	public static function deleteAll($condition = '', $params = [])
w  
Qiang Xue committed
196
	{
Qiang Xue committed
197
		$command = static::getDb()->createCommand();
Qiang Xue committed
198 199
		$command->delete(static::tableName(), $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
200 201
	}

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

	/**
Qiang Xue committed
232
	 * Declares the name of the database table associated with this AR class.
233
	 * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
234
	 * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is 'tbl_',
235 236
	 * '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
237 238
	 * @return string the table name
	 */
Qiang Xue committed
239
	public static function tableName()
w  
Qiang Xue committed
240
	{
241
		return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
w  
Qiang Xue committed
242 243 244
	}

	/**
Qiang Xue committed
245 246
	 * 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.
247
	 * @throws InvalidConfigException if the table for the AR class does not exist.
w  
Qiang Xue committed
248
	 */
Qiang Xue committed
249
	public static function getTableSchema()
w  
Qiang Xue committed
250
	{
251 252 253 254 255 256
		$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
257 258 259
	}

	/**
Qiang Xue committed
260 261
	 * Returns the primary key name(s) for this AR class.
	 * The default implementation will return the primary key(s) as declared
Qiang Xue committed
262
	 * in the DB table that is associated with this AR class.
Qiang Xue committed
263
	 *
Qiang Xue committed
264 265 266
	 * 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
267 268 269
	 *
	 * Note that an array should be returned even for a table with single primary key.
	 *
Qiang Xue committed
270
	 * @return string[] the primary keys of the associated database table.
w  
Qiang Xue committed
271
	 */
Qiang Xue committed
272
	public static function primaryKey()
w  
Qiang Xue committed
273
	{
Qiang Xue committed
274
		return static::getTableSchema()->primaryKey;
w  
Qiang Xue committed
275 276
	}

277
	/**
278 279 280
	 * 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.
281
	 */
282
	public function attributes()
283
	{
284
		return array_keys(static::getTableSchema()->columns);
285 286
	}

287 288 289 290 291 292 293 294 295 296 297
	/**
	 * 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
298
	 * return [
299 300 301 302 303
	 *     '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
304
	 * ];
305 306 307 308 309 310 311 312 313 314 315
	 * ~~~
	 *
	 * 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
316
		return [];
317 318
	}

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

Qiang Xue committed
333
	/**
Qiang Xue committed
334 335 336 337 338 339
	 * 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;
340 341
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
Qiang Xue committed
342
	 *    rest of the steps;
343 344
	 * 4. insert the record into database. If this fails, it will skip the rest of the steps;
	 * 5. call [[afterSave()]];
Qiang Xue committed
345
	 *
346
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
Qiang Xue committed
347 348
	 * [[EVENT_BEFORE_INSERT]], [[EVENT_AFTER_INSERT]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
Qiang Xue committed
349
	 *
350
	 * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
Qiang Xue committed
351 352
	 *
	 * If the table's primary key is auto-incremental and is null during insertion,
Qiang Xue committed
353
	 * it will be populated with the actual value after insertion.
Qiang Xue committed
354 355 356 357 358 359 360 361 362 363 364 365
	 *
	 * 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
366 367 368
	 * @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.
369
	 * @throws \Exception in case insert failed.
Qiang Xue committed
370
	 */
Qiang Xue committed
371
	public function insert($runValidation = true, $attributes = null)
Qiang Xue committed
372
	{
373 374 375 376
		if ($runValidation && !$this->validate($attributes)) {
			return false;
		}
		$db = static::getDb();
Qiang Xue committed
377
		if ($this->isTransactional(self::OP_INSERT)) {
Qiang Xue committed
378 379 380
			$transaction = $db->beginTransaction();
			try {
				$result = $this->insertInternal($attributes);
resurtm committed
381
				if ($result === false) {
382
					$transaction->rollBack();
383 384 385
				} else {
					$transaction->commit();
				}
Qiang Xue committed
386
			} catch (\Exception $e) {
387
				$transaction->rollBack();
Qiang Xue committed
388
				throw $e;
389
			}
Qiang Xue committed
390 391
		} else {
			$result = $this->insertInternal($attributes);
392 393 394 395 396
		}
		return $result;
	}

	/**
Qiang Xue committed
397 398 399 400
	 * Inserts an ActiveRecord into DB without considering transaction.
	 * @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 record is inserted successfully.
401
	 */
Qiang Xue committed
402
	protected 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
		if ($this->isTransactional(self::OP_UPDATE)) {
Qiang Xue committed
493 494 495
			$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();
Qiang Xue committed
533 534 535 536
		if ($this->isTransactional(self::OP_DELETE)) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->deleteInternal();
resurtm committed
537
				if ($result === false) {
538
					$transaction->rollBack();
539 540 541
				} else {
					$transaction->commit();
				}
Qiang Xue committed
542
			} catch (\Exception $e) {
543
				$transaction->rollBack();
Qiang Xue committed
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
				throw $e;
			}
		} else {
			$result = $this->deleteInternal();
		}

		return $result;
	}

	/**
	 * Deletes an ActiveRecord without considering transaction.
	 * @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.
	 * @throws StaleObjectException
	 */
	protected function deleteInternal()
	{
		$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();
			if ($lock !== null) {
				$condition[$lock] = $this->$lock;
			}
			$result = $this->deleteAll($condition);
			if ($lock !== null && !$result) {
				throw new StaleObjectException('The object being deleted is outdated.');
573
			}
Qiang Xue committed
574 575
			$this->setOldAttributes(null);
			$this->afterDelete();
Qiang Xue committed
576
		}
577
		return $result;
w  
Qiang Xue committed
578 579 580
	}

	/**
Qiang Xue committed
581 582
	 * 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.
583
	 * If one of the records [[isNewRecord|is new]] they are also considered not equal.
Qiang Xue committed
584
	 * @param ActiveRecord $record record to compare to
Qiang Xue committed
585
	 * @return boolean whether the two active records refer to the same row in the same database table.
w  
Qiang Xue committed
586
	 */
Qiang Xue committed
587
	public function equals($record)
w  
Qiang Xue committed
588
	{
589 590 591
		if ($this->isNewRecord || $record->isNewRecord) {
			return false;
		}
Qiang Xue committed
592
		return $this->tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
w  
Qiang Xue committed
593 594
	}

595
	/**
596 597 598
	 * 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]].
599
	 */
600
	public function isTransactional($operation)
601 602
	{
		$scenario = $this->getScenario();
603 604
		$transactions = $this->transactions();
		return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
605
	}
w  
Qiang Xue committed
606
}