ActiveRecord.php 18.2 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
 *
Qiang Xue committed
18
 * @include @yii/db/ActiveRecord.md
w  
Qiang Xue committed
19
 *
Qiang Xue committed
20
 * @author Qiang Xue <qiang.xue@gmail.com>
21
 * @author Carsten Brandt <mail@cebe.cc>
Qiang Xue committed
22
 * @since 2.0
w  
Qiang Xue committed
23
 */
24
class ActiveRecord extends BaseActiveRecord
w  
Qiang Xue committed
25
{
26
	/**
27
	 * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
28
	 */
29
	const OP_INSERT = 0x01;
30
	/**
31
	 * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
32
	 */
33
	const OP_UPDATE = 0x02;
34
	/**
35
	 * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
36
	 */
37 38 39 40 41 42
	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;
43

Qiang Xue committed
44 45 46 47 48 49
	/**
	 * 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
50
	public static function getDb()
Qiang Xue committed
51
	{
Qiang Xue committed
52
		return \Yii::$app->getDb();
Qiang Xue committed
53 54
	}

Qiang Xue committed
55
	/**
Qiang Xue committed
56 57 58 59 60 61 62 63 64 65 66 67 68
	 * 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
69 70
	 * @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
71
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance
Qiang Xue committed
72
	 */
Alexander Makarov committed
73
	public static function findBySql($sql, $params = [])
w  
Qiang Xue committed
74
	{
Qiang Xue committed
75
		$query = static::createQuery();
Qiang Xue committed
76 77 78 79 80 81
		$query->sql = $sql;
		return $query->params($params);
	}

	/**
	 * Updates the whole table using the provided attribute values and conditions.
Qiang Xue committed
82 83 84
	 * For example, to change the status to be 1 for all customers whose status is 2:
	 *
	 * ~~~
Alexander Makarov committed
85
	 * Customer::updateAll(['status' => 1], 'status = 2');
Qiang Xue committed
86 87 88 89
	 * ~~~
	 *
	 * @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
90
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
91
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
92 93
	 * @return integer the number of rows updated
	 */
Alexander Makarov committed
94
	public static function updateAll($attributes, $condition = '', $params = [])
w  
Qiang Xue committed
95
	{
Qiang Xue committed
96
		$command = static::getDb()->createCommand();
Qiang Xue committed
97 98
		$command->update(static::tableName(), $attributes, $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
99 100
	}

Qiang Xue committed
101
	/**
Qiang Xue committed
102 103 104 105
	 * Updates the whole table using the provided counter changes and conditions.
	 * For example, to increment all customers' age by 1,
	 *
	 * ~~~
Alexander Makarov committed
106
	 * Customer::updateAllCounters(['age' => 1]);
Qiang Xue committed
107 108
	 * ~~~
	 *
Qiang Xue committed
109
	 * @param array $counters the counters to be updated (attribute name => increment value).
Qiang Xue committed
110 111
	 * 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
112
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
113
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
114
	 * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
Qiang Xue committed
115 116
	 * @return integer the number of rows updated
	 */
Alexander Makarov committed
117
	public static function updateAllCounters($counters, $condition = '', $params = [])
w  
Qiang Xue committed
118
	{
Qiang Xue committed
119
		$n = 0;
Qiang Xue committed
120
		foreach ($counters as $name => $value) {
Alexander Makarov committed
121
			$counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
Qiang Xue committed
122
			$n++;
Qiang Xue committed
123
		}
124
		$command = static::getDb()->createCommand();
Qiang Xue committed
125 126
		$command->update(static::tableName(), $counters, $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
127 128
	}

Qiang Xue committed
129 130
	/**
	 * Deletes rows in the table using the provided conditions.
Qiang Xue committed
131 132 133 134 135 136 137 138 139
	 * 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
140
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
141
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
142
	 * @return integer the number of rows deleted
Qiang Xue committed
143
	 */
Alexander Makarov committed
144
	public static function deleteAll($condition = '', $params = [])
w  
Qiang Xue committed
145
	{
Qiang Xue committed
146
		$command = static::getDb()->createCommand();
Qiang Xue committed
147 148
		$command->delete(static::tableName(), $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
149 150
	}

.  
Qiang Xue committed
151
	/**
Qiang Xue committed
152
	 * Creates an [[ActiveQuery]] instance.
153
	 * This method is called by [[find()]], [[findBySql()]] to start a SELECT query.
Qiang Xue committed
154 155
	 * You may override this method to return a customized query (e.g. `CustomerQuery` specified
	 * written for querying `Customer` purpose.)
Qiang Xue committed
156
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance.
.  
Qiang Xue committed
157
	 */
Qiang Xue committed
158
	public static function createQuery()
w  
Qiang Xue committed
159
	{
Alexander Makarov committed
160
		return new ActiveQuery(['modelClass' => get_called_class()]);
w  
Qiang Xue committed
161 162 163
	}

	/**
Qiang Xue committed
164
	 * Declares the name of the database table associated with this AR class.
165
	 * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
Qiang Xue committed
166 167
	 * with prefix 'tbl_'. For example, '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
168 169
	 * @return string the table name
	 */
Qiang Xue committed
170
	public static function tableName()
w  
Qiang Xue committed
171
	{
172
		return 'tbl_' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
w  
Qiang Xue committed
173 174 175
	}

	/**
Qiang Xue committed
176 177
	 * 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.
178
	 * @throws InvalidConfigException if the table for the AR class does not exist.
w  
Qiang Xue committed
179
	 */
Qiang Xue committed
180
	public static function getTableSchema()
w  
Qiang Xue committed
181
	{
182 183 184 185 186 187
		$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
188 189 190
	}

	/**
Qiang Xue committed
191 192
	 * Returns the primary key name(s) for this AR class.
	 * The default implementation will return the primary key(s) as declared
Qiang Xue committed
193
	 * in the DB table that is associated with this AR class.
Qiang Xue committed
194
	 *
Qiang Xue committed
195 196 197
	 * 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
198 199 200
	 *
	 * Note that an array should be returned even for a table with single primary key.
	 *
Qiang Xue committed
201
	 * @return string[] the primary keys of the associated database table.
w  
Qiang Xue committed
202
	 */
Qiang Xue committed
203
	public static function primaryKey()
w  
Qiang Xue committed
204
	{
Qiang Xue committed
205
		return static::getTableSchema()->primaryKey;
w  
Qiang Xue committed
206 207
	}

208
	/**
209 210 211
	 * 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.
212
	 */
213
	public function attributes()
214
	{
215
		return array_keys(static::getTableSchema()->columns);
216 217
	}

218 219 220 221 222 223 224 225 226 227 228
	/**
	 * 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
229
	 * return [
230 231 232 233 234
	 *     '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
235
	 * ];
236 237 238 239 240 241 242 243 244 245 246
	 * ~~~
	 *
	 * 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
247
		return [];
248 249
	}

250 251 252 253 254 255 256
	/**
	 * Creates an [[ActiveRelation]] instance.
	 * This method is called by [[hasOne()]] and [[hasMany()]] to create a relation instance.
	 * You may override this method to return a customized relation.
	 * @param array $config the configuration passed to the ActiveRelation class.
	 * @return ActiveRelation the newly created [[ActiveRelation]] instance.
	 */
257
	public static function createActiveRelation($config = [])
258 259
	{
		return new ActiveRelation($config);
Qiang Xue committed
260 261
	}

Qiang Xue committed
262
	/**
Qiang Xue committed
263 264 265 266 267 268
	 * 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;
269 270
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
Qiang Xue committed
271
	 *    rest of the steps;
272 273
	 * 4. insert the record into database. If this fails, it will skip the rest of the steps;
	 * 5. call [[afterSave()]];
Qiang Xue committed
274
	 *
275
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
Qiang Xue committed
276 277
	 * [[EVENT_BEFORE_INSERT]], [[EVENT_AFTER_INSERT]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
Qiang Xue committed
278
	 *
279
	 * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
Qiang Xue committed
280 281
	 *
	 * If the table's primary key is auto-incremental and is null during insertion,
Qiang Xue committed
282
	 * it will be populated with the actual value after insertion.
Qiang Xue committed
283 284 285 286 287 288 289 290 291 292 293 294
	 *
	 * 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
295 296 297
	 * @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.
298
	 * @throws \Exception in case insert failed.
Qiang Xue committed
299
	 */
Qiang Xue committed
300
	public function insert($runValidation = true, $attributes = null)
Qiang Xue committed
301
	{
302 303 304 305
		if ($runValidation && !$this->validate($attributes)) {
			return false;
		}
		$db = static::getDb();
Qiang Xue committed
306 307 308 309
		if ($this->isTransactional(self::OP_INSERT) && $db->getTransaction() === null) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->insertInternal($attributes);
resurtm committed
310
				if ($result === false) {
311 312 313 314
					$transaction->rollback();
				} else {
					$transaction->commit();
				}
Qiang Xue committed
315
			} catch (\Exception $e) {
316
				$transaction->rollback();
Qiang Xue committed
317
				throw $e;
318
			}
Qiang Xue committed
319 320
		} else {
			$result = $this->insertInternal($attributes);
321 322 323 324 325 326 327
		}
		return $result;
	}

	/**
	 * @see ActiveRecord::insert()
	 */
resurtm committed
328
	private function insertInternal($attributes = null)
329 330
	{
		if (!$this->beforeSave(true)) {
Qiang Xue committed
331 332
			return false;
		}
333 334
		$values = $this->getDirtyAttributes($attributes);
		if (empty($values)) {
335 336
			foreach ($this->getPrimaryKey(true) as $key => $value) {
				$values[$key] = $value;
Qiang Xue committed
337
			}
338 339 340
		}
		$db = static::getDb();
		$command = $db->createCommand()->insert($this->tableName(), $values);
341 342 343 344 345 346
		if (!$command->execute()) {
			return false;
		}
		$table = $this->getTableSchema();
		if ($table->sequenceName !== null) {
			foreach ($table->primaryKey as $name) {
347 348 349 350
				if ($this->getAttribute($name) === null) {
					$id = $db->getLastInsertID($table->sequenceName);
					$this->setAttribute($name, $id);
					$this->setOldAttribute($name, $id);
351
					break;
Qiang Xue committed
352 353 354
				}
			}
		}
355
		foreach ($values as $name => $value) {
356
			$this->setOldAttribute($name, $value);
357 358 359
		}
		$this->afterSave(true);
		return true;
Qiang Xue committed
360 361 362
	}

	/**
Qiang Xue committed
363 364 365 366 367 368
	 * 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;
369 370
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
Qiang Xue committed
371
	 *    rest of the steps;
372 373
	 * 4. save the record into database. If this fails, it will skip the rest of the steps;
	 * 5. call [[afterSave()]];
Qiang Xue committed
374
	 *
375
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
Qiang Xue committed
376 377
	 * [[EVENT_BEFORE_UPDATE]], [[EVENT_AFTER_UPDATE]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
Qiang Xue committed
378 379 380 381 382 383 384 385 386 387 388 389
	 *
	 * Only the [[changedAttributes|changed attribute values]] will be saved into database.
	 *
	 * For example, to update a customer record:
	 *
	 * ~~~
	 * $customer = Customer::find($id);
	 * $customer->name = $name;
	 * $customer->email = $email;
	 * $customer->update();
	 * ~~~
	 *
390 391 392 393 394 395 396 397 398 399 400 401
	 * 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
402 403
	 * @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
404 405
	 * @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.
406 407
	 * @return integer|boolean the number of rows affected, or false if validation fails
	 * or [[beforeSave()]] stops the updating process.
408
	 * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
409
	 * being updated is outdated.
410
	 * @throws \Exception in case update failed.
Qiang Xue committed
411
	 */
Qiang Xue committed
412
	public function update($runValidation = true, $attributes = null)
Qiang Xue committed
413
	{
414
		if ($runValidation && !$this->validate($attributes)) {
Qiang Xue committed
415 416
			return false;
		}
417
		$db = static::getDb();
Qiang Xue committed
418 419 420 421
		if ($this->isTransactional(self::OP_UPDATE) && $db->getTransaction() === null) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->updateInternal($attributes);
resurtm committed
422
				if ($result === false) {
423 424 425
					$transaction->rollback();
				} else {
					$transaction->commit();
426
				}
Qiang Xue committed
427
			} catch (\Exception $e) {
428
				$transaction->rollback();
Qiang Xue committed
429
				throw $e;
430
			}
Qiang Xue committed
431 432
		} else {
			$result = $this->updateInternal($attributes);
433 434 435
		}
		return $result;
	}
436

Qiang Xue committed
437
	/**
Qiang Xue committed
438 439 440 441 442 443 444 445 446
	 * 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
447
	 * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
Qiang Xue committed
448 449
	 * will be raised by the corresponding methods.
	 *
450 451
	 * @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.
452
	 * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
453
	 * being deleted is outdated.
454
	 * @throws \Exception in case delete failed.
Qiang Xue committed
455 456 457
	 */
	public function delete()
	{
458
		$db = static::getDb();
459
		$transaction = $this->isTransactional(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
460 461 462 463 464 465 466
		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
467
				if ($lock !== null) {
468 469 470
					$condition[$lock] = $this->$lock;
				}
				$result = $this->deleteAll($condition);
resurtm committed
471
				if ($lock !== null && !$result) {
472 473
					throw new StaleObjectException('The object being deleted is outdated.');
				}
474
				$this->setOldAttributes(null);
475
				$this->afterDelete();
476
			}
resurtm committed
477 478
			if ($transaction !== null) {
				if ($result === false) {
479 480 481 482
					$transaction->rollback();
				} else {
					$transaction->commit();
				}
483
			}
484
		} catch (\Exception $e) {
resurtm committed
485
			if ($transaction !== null) {
486 487 488
				$transaction->rollback();
			}
			throw $e;
Qiang Xue committed
489
		}
490
		return $result;
w  
Qiang Xue committed
491 492 493
	}

	/**
Qiang Xue committed
494 495
	 * 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.
496
	 * If one of the records [[isNewRecord|is new]] they are also considered not equal.
Qiang Xue committed
497
	 * @param ActiveRecord $record record to compare to
Qiang Xue committed
498
	 * @return boolean whether the two active records refer to the same row in the same database table.
w  
Qiang Xue committed
499
	 */
Qiang Xue committed
500
	public function equals($record)
w  
Qiang Xue committed
501
	{
502 503 504
		if ($this->isNewRecord || $record->isNewRecord) {
			return false;
		}
Qiang Xue committed
505
		return $this->tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
w  
Qiang Xue committed
506 507
	}

508
	/**
509 510 511
	 * 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]].
512
	 */
513
	public function isTransactional($operation)
514 515
	{
		$scenario = $this->getScenario();
516 517
		$transactions = $this->transactions();
		return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
518
	}
w  
Qiang Xue committed
519
}