ActiveRecord.php 51.5 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;
Qiang Xue committed
12
use yii\base\Model;
Qiang Xue committed
13
use yii\base\InvalidParamException;
Qiang Xue committed
14
use yii\base\ModelEvent;
Qiang Xue committed
15 16
use yii\base\UnknownMethodException;
use yii\base\InvalidCallException;
Qiang Xue committed
17
use yii\helpers\StringHelper;
18
use yii\helpers\Inflector;
w  
Qiang Xue committed
19

w  
Qiang Xue committed
20
/**
Qiang Xue committed
21
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
w  
Qiang Xue committed
22
 *
Qiang Xue committed
23
 * @include @yii/db/ActiveRecord.md
w  
Qiang Xue committed
24
 *
25 26 27 28 29 30 31
 * @property array $dirtyAttributes The changed attribute values (name-value pairs). This property is
 * read-only.
 * @property boolean $isNewRecord Whether the record is new and should be inserted when calling [[save()]].
 * @property array $oldAttributes The old attribute values (name-value pairs).
 * @property mixed $oldPrimaryKey The old primary key value. An array (column name => column value) is
 * returned if the primary key is composite or `$asArray` is true. A string is returned otherwise (null will be
 * returned if the key value is null). This property is read-only.
32 33
 * @property array $populatedRelations An array of relation data indexed by relation names. This property is
 * read-only.
34 35 36
 * @property mixed $primaryKey The primary key value. An array (column name => column value) is returned if
 * the primary key is composite or `$asArray` is true. A string is returned otherwise (null will be returned if
 * the key value is null). This property is read-only.
Qiang Xue committed
37
 *
Qiang Xue committed
38
 * @author Qiang Xue <qiang.xue@gmail.com>
39
 * @author Carsten Brandt <mail@cebe.cc>
Qiang Xue committed
40
 * @since 2.0
w  
Qiang Xue committed
41
 */
Qiang Xue committed
42
class ActiveRecord extends Model
w  
Qiang Xue committed
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 73 74 75 76 77 78 79
	/**
	 * @event Event an event that is triggered when the record is initialized via [[init()]].
	 */
	const EVENT_INIT = 'init';
	/**
	 * @event Event an event that is triggered after the record is created and populated with query result.
	 */
	const EVENT_AFTER_FIND = 'afterFind';
	/**
	 * @event ModelEvent an event that is triggered before inserting a record.
	 * You may set [[ModelEvent::isValid]] to be false to stop the insertion.
	 */
	const EVENT_BEFORE_INSERT = 'beforeInsert';
	/**
	 * @event Event an event that is triggered after a record is inserted.
	 */
	const EVENT_AFTER_INSERT = 'afterInsert';
	/**
	 * @event ModelEvent an event that is triggered before updating a record.
	 * You may set [[ModelEvent::isValid]] to be false to stop the update.
	 */
	const EVENT_BEFORE_UPDATE = 'beforeUpdate';
	/**
	 * @event Event an event that is triggered after a record is updated.
	 */
	const EVENT_AFTER_UPDATE = 'afterUpdate';
	/**
	 * @event ModelEvent an event that is triggered before deleting a record.
	 * You may set [[ModelEvent::isValid]] to be false to stop the deletion.
	 */
	const EVENT_BEFORE_DELETE = 'beforeDelete';
	/**
	 * @event Event an event that is triggered after a record is deleted.
	 */
	const EVENT_AFTER_DELETE = 'afterDelete';

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

w  
Qiang Xue committed
98
	/**
Qiang Xue committed
99 100
	 * @var array attribute values indexed by attribute names
	 */
Alexander Makarov committed
101
	private $_attributes = [];
Qiang Xue committed
102 103
	/**
	 * @var array old attribute values indexed by attribute names.
w  
Qiang Xue committed
104
	 */
Qiang Xue committed
105
	private $_oldAttributes;
106
	/**
Qiang Xue committed
107
	 * @var array related models indexed by the relation names
108
	 */
109
	private $_related = [];
Qiang Xue committed
110

111

Qiang Xue committed
112 113 114 115 116 117
	/**
	 * 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
118
	public static function getDb()
Qiang Xue committed
119
	{
Qiang Xue committed
120
		return \Yii::$app->getDb();
Qiang Xue committed
121 122
	}

Qiang Xue committed
123
	/**
Qiang Xue committed
124
	 * Creates an [[ActiveQuery]] instance for query purpose.
Qiang Xue committed
125
	 *
Qiang Xue committed
126
	 * @include @yii/db/ActiveRecord-find.md
Qiang Xue committed
127 128 129
	 *
	 * @param mixed $q the query parameter. This can be one of the followings:
	 *
Qiang Xue committed
130 131
	 *  - a scalar value (integer or string): query by a single primary key value and return the
	 *    corresponding record.
Qiang Xue committed
132
	 *  - an array of name-value pairs: query by a set of column values and return a single record matching all of them.
Qiang Xue committed
133
	 *  - null: return a new [[ActiveQuery]] object for further query purpose.
Qiang Xue committed
134
	 *
Qiang Xue committed
135 136
	 * @return ActiveQuery|ActiveRecord|null When `$q` is null, a new [[ActiveQuery]] instance
	 * is returned; when `$q` is a scalar or an array, an ActiveRecord object matching it will be
Qiang Xue committed
137
	 * returned (null will be returned if there is no matching).
Qiang Xue committed
138
	 * @throws InvalidConfigException if the AR class does not have a primary key
Qiang Xue committed
139
	 * @see createQuery()
Qiang Xue committed
140 141 142
	 */
	public static function find($q = null)
	{
Qiang Xue committed
143
		$query = static::createQuery();
Qiang Xue committed
144
		if (is_array($q)) {
Qiang Xue committed
145
			return $query->where($q)->one();
Qiang Xue committed
146 147
		} elseif ($q !== null) {
			// query by primary key
Qiang Xue committed
148
			$primaryKey = static::primaryKey();
Qiang Xue committed
149
			if (isset($primaryKey[0])) {
Alexander Makarov committed
150
				return $query->where([$primaryKey[0] => $q])->one();
Qiang Xue committed
151 152 153
			} else {
				throw new InvalidConfigException(get_called_class() . ' must have a primary key.');
			}
Qiang Xue committed
154
		}
Qiang Xue committed
155
		return $query;
w  
Qiang Xue committed
156 157
	}

Qiang Xue committed
158
	/**
Qiang Xue committed
159 160 161 162 163 164 165 166 167 168 169 170 171
	 * 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
172 173
	 * @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
174
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance
Qiang Xue committed
175
	 */
Alexander Makarov committed
176
	public static function findBySql($sql, $params = [])
w  
Qiang Xue committed
177
	{
Qiang Xue committed
178
		$query = static::createQuery();
Qiang Xue committed
179 180 181 182 183 184
		$query->sql = $sql;
		return $query->params($params);
	}

	/**
	 * Updates the whole table using the provided attribute values and conditions.
Qiang Xue committed
185 186 187
	 * For example, to change the status to be 1 for all customers whose status is 2:
	 *
	 * ~~~
Alexander Makarov committed
188
	 * Customer::updateAll(['status' => 1], 'status = 2');
Qiang Xue committed
189 190 191 192
	 * ~~~
	 *
	 * @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
193
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
194
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
195 196
	 * @return integer the number of rows updated
	 */
Alexander Makarov committed
197
	public static function updateAll($attributes, $condition = '', $params = [])
w  
Qiang Xue committed
198
	{
Qiang Xue committed
199
		$command = static::getDb()->createCommand();
Qiang Xue committed
200 201
		$command->update(static::tableName(), $attributes, $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
202 203
	}

Qiang Xue committed
204
	/**
Qiang Xue committed
205 206 207 208
	 * Updates the whole table using the provided counter changes and conditions.
	 * For example, to increment all customers' age by 1,
	 *
	 * ~~~
Alexander Makarov committed
209
	 * Customer::updateAllCounters(['age' => 1]);
Qiang Xue committed
210 211
	 * ~~~
	 *
Qiang Xue committed
212
	 * @param array $counters the counters to be updated (attribute name => increment value).
Qiang Xue committed
213 214
	 * 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
215
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
216
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
217
	 * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
Qiang Xue committed
218 219
	 * @return integer the number of rows updated
	 */
Alexander Makarov committed
220
	public static function updateAllCounters($counters, $condition = '', $params = [])
w  
Qiang Xue committed
221
	{
Qiang Xue committed
222
		$n = 0;
Qiang Xue committed
223
		foreach ($counters as $name => $value) {
Alexander Makarov committed
224
			$counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
Qiang Xue committed
225
			$n++;
Qiang Xue committed
226
		}
227
		$command = static::getDb()->createCommand();
Qiang Xue committed
228 229
		$command->update(static::tableName(), $counters, $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
230 231
	}

Qiang Xue committed
232 233
	/**
	 * Deletes rows in the table using the provided conditions.
Qiang Xue committed
234 235 236 237 238 239 240 241 242
	 * 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
243
	 * Please refer to [[Query::where()]] on how to specify this parameter.
resurtm committed
244
	 * @param array $params the parameters (name => value) to be bound to the query.
Qiang Xue committed
245
	 * @return integer the number of rows deleted
Qiang Xue committed
246
	 */
Alexander Makarov committed
247
	public static function deleteAll($condition = '', $params = [])
w  
Qiang Xue committed
248
	{
Qiang Xue committed
249
		$command = static::getDb()->createCommand();
Qiang Xue committed
250 251
		$command->delete(static::tableName(), $condition, $params);
		return $command->execute();
w  
Qiang Xue committed
252 253
	}

.  
Qiang Xue committed
254
	/**
Qiang Xue committed
255
	 * Creates an [[ActiveQuery]] instance.
256
	 * This method is called by [[find()]], [[findBySql()]] to start a SELECT query.
Qiang Xue committed
257 258
	 * You may override this method to return a customized query (e.g. `CustomerQuery` specified
	 * written for querying `Customer` purpose.)
Qiang Xue committed
259
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance.
.  
Qiang Xue committed
260
	 */
Qiang Xue committed
261
	public static function createQuery()
w  
Qiang Xue committed
262
	{
Alexander Makarov committed
263
		return new ActiveQuery(['modelClass' => get_called_class()]);
w  
Qiang Xue committed
264 265 266
	}

	/**
Qiang Xue committed
267
	 * Declares the name of the database table associated with this AR class.
268
	 * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
Qiang Xue committed
269 270
	 * 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
271 272
	 * @return string the table name
	 */
Qiang Xue committed
273
	public static function tableName()
w  
Qiang Xue committed
274
	{
275
		return 'tbl_' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
w  
Qiang Xue committed
276 277 278
	}

	/**
Qiang Xue committed
279 280
	 * 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.
281
	 * @throws InvalidConfigException if the table for the AR class does not exist.
w  
Qiang Xue committed
282
	 */
Qiang Xue committed
283
	public static function getTableSchema()
w  
Qiang Xue committed
284
	{
285 286 287 288 289 290
		$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
291 292 293
	}

	/**
Qiang Xue committed
294 295
	 * Returns the primary key name(s) for this AR class.
	 * The default implementation will return the primary key(s) as declared
Qiang Xue committed
296
	 * in the DB table that is associated with this AR class.
Qiang Xue committed
297
	 *
Qiang Xue committed
298 299 300
	 * 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
301 302 303
	 *
	 * Note that an array should be returned even for a table with single primary key.
	 *
Qiang Xue committed
304
	 * @return string[] the primary keys of the associated database table.
w  
Qiang Xue committed
305
	 */
Qiang Xue committed
306
	public static function primaryKey()
w  
Qiang Xue committed
307
	{
Qiang Xue committed
308
		return static::getTableSchema()->primaryKey;
w  
Qiang Xue committed
309 310
	}

311
	/**
312
	 * Returns the name of the column that stores the lock version for implementing optimistic locking.
313
	 *
314 315 316 317
	 * Optimistic locking allows multiple users to access the same record for edits and avoids
	 * potential conflicts. In case when a user attempts to save the record upon some staled data
	 * (because another user has modified the data), a [[StaleObjectException]] exception will be thrown,
	 * and the update or deletion is skipped.
318 319 320 321 322
	 *
	 * Optimized locking is only supported by [[update()]] and [[delete()]].
	 *
	 * To use optimized locking:
	 *
323
	 * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`.
324
	 *    Override this method to return the name of this column.
325 326 327 328 329 330 331 332 333
	 * 2. In the Web form that collects the user input, add a hidden field that stores
	 *    the lock version of the recording being updated.
	 * 3. In the controller action that does the data updating, try to catch the [[StaleObjectException]]
	 *    and implement necessary business logic (e.g. merging the changes, prompting stated data)
	 *    to resolve the conflict.
	 *
	 * @return string the column name that stores the lock version of a table row.
	 * If null is returned (default implemented), optimistic locking will not be supported.
	 */
334
	public function optimisticLock()
335 336 337 338
	{
		return null;
	}

339 340 341 342 343 344 345 346 347 348 349
	/**
	 * 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
350
	 * return [
351 352 353 354 355
	 *     '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
356
	 * ];
357 358 359 360 361 362 363 364 365 366 367
	 * ~~~
	 *
	 * 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
368
		return [];
369 370
	}

w  
Qiang Xue committed
371
	/**
Qiang Xue committed
372
	 * PHP getter magic method.
Qiang Xue committed
373
	 * This method is overridden so that attributes and related objects can be accessed like properties.
Qiang Xue committed
374 375
	 * @param string $name property name
	 * @return mixed property value
376
	 * @see getAttribute()
Qiang Xue committed
377 378 379
	 */
	public function __get($name)
	{
Qiang Xue committed
380
		if (isset($this->_attributes[$name]) || array_key_exists($name, $this->_attributes)) {
Qiang Xue committed
381
			return $this->_attributes[$name];
382
		} elseif ($this->hasAttribute($name)) {
Qiang Xue committed
383
			return null;
Qiang Xue committed
384
		} else {
385 386
			if (isset($this->_related[$name]) || array_key_exists($name, $this->_related)) {
				return $this->_related[$name];
Qiang Xue committed
387 388
			}
			$value = parent::__get($name);
389
			if ($value instanceof ActiveRelationInterface) {
390
				return $this->_related[$name] = $value->multiple ? $value->all() : $value->one();
Qiang Xue committed
391
			} else {
Qiang Xue committed
392
				return $value;
Qiang Xue committed
393
			}
Qiang Xue committed
394 395 396 397 398 399 400 401 402 403 404
		}
	}

	/**
	 * PHP setter magic method.
	 * This method is overridden so that AR attributes can be accessed like properties.
	 * @param string $name property name
	 * @param mixed $value property value
	 */
	public function __set($name, $value)
	{
405
		if ($this->hasAttribute($name)) {
Qiang Xue committed
406 407 408 409 410 411 412 413
			$this->_attributes[$name] = $value;
		} else {
			parent::__set($name, $value);
		}
	}

	/**
	 * Checks if a property value is null.
Qiang Xue committed
414
	 * This method overrides the parent implementation by checking if the named attribute is null or not.
Qiang Xue committed
415 416 417 418
	 * @param string $name the property name or the event name
	 * @return boolean whether the property value is null
	 */
	public function __isset($name)
w  
Qiang Xue committed
419
	{
Qiang Xue committed
420 421 422 423
		try {
			return $this->__get($name) !== null;
		} catch (\Exception $e) {
			return false;
Qiang Xue committed
424 425 426 427 428 429 430 431 432 433 434
		}
	}

	/**
	 * Sets a component property to be null.
	 * This method overrides the parent implementation by clearing
	 * the specified attribute value.
	 * @param string $name the property name or the event name
	 */
	public function __unset($name)
	{
435
		if ($this->hasAttribute($name)) {
Qiang Xue committed
436
			unset($this->_attributes[$name]);
Qiang Xue committed
437
		} else {
438 439
			if (isset($this->_related[$name])) {
				unset($this->_related[$name]);
Qiang Xue committed
440 441 442
			} else {
				parent::__unset($name);
			}
Qiang Xue committed
443 444 445
		}
	}

Qiang Xue committed
446 447 448 449
	/**
	 * Declares a `has-one` relation.
	 * The declaration is returned in terms of an [[ActiveRelation]] instance
	 * through which the related record can be queried and retrieved back.
Qiang Xue committed
450 451 452 453 454 455 456 457 458 459
	 *
	 * A `has-one` relation means that there is at most one related record matching
	 * the criteria set by this relation, e.g., a customer has one country.
	 *
	 * For example, to declare the `country` relation for `Customer` class, we can write
	 * the following code in the `Customer` class:
	 *
	 * ~~~
	 * public function getCountry()
	 * {
460
	 *     return $this->hasOne(Country::className(), ['id' => 'country_id']);
Qiang Xue committed
461 462 463 464 465 466 467 468 469
	 * }
	 * ~~~
	 *
	 * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
	 * in the related class `Country`, while the 'country_id' value refers to an attribute name
	 * in the current AR class.
	 *
	 * Call methods declared in [[ActiveRelation]] to further customize the relation.
	 *
Qiang Xue committed
470 471 472 473 474 475
	 * @param string $class the class name of the related record
	 * @param array $link the primary-foreign key constraint. The keys of the array refer to
	 * the columns in the table associated with the `$class` model, while the values of the
	 * array refer to the corresponding columns in the table associated with this AR class.
	 * @return ActiveRelation the relation object.
	 */
Qiang Xue committed
476
	public function hasOne($class, $link)
Qiang Xue committed
477
	{
478
		return $this->createActiveRelation([
479
			'modelClass' => $class,
Qiang Xue committed
480 481 482
			'primaryModel' => $this,
			'link' => $link,
			'multiple' => false,
Alexander Makarov committed
483
		]);
Qiang Xue committed
484 485
	}

Qiang Xue committed
486 487 488 489
	/**
	 * Declares a `has-many` relation.
	 * The declaration is returned in terms of an [[ActiveRelation]] instance
	 * through which the related record can be queried and retrieved back.
Qiang Xue committed
490 491 492 493 494 495 496 497 498 499
	 *
	 * A `has-many` relation means that there are multiple related records matching
	 * the criteria set by this relation, e.g., a customer has many orders.
	 *
	 * For example, to declare the `orders` relation for `Customer` class, we can write
	 * the following code in the `Customer` class:
	 *
	 * ~~~
	 * public function getOrders()
	 * {
500
	 *     return $this->hasMany(Order::className(), ['customer_id' => 'id']);
Qiang Xue committed
501 502 503 504 505 506 507
	 * }
	 * ~~~
	 *
	 * Note that in the above, the 'customer_id' key in the `$link` parameter refers to
	 * an attribute name in the related class `Order`, while the 'id' value refers to
	 * an attribute name in the current AR class.
	 *
Qiang Xue committed
508 509 510 511 512 513
	 * @param string $class the class name of the related record
	 * @param array $link the primary-foreign key constraint. The keys of the array refer to
	 * the columns in the table associated with the `$class` model, while the values of the
	 * array refer to the corresponding columns in the table associated with this AR class.
	 * @return ActiveRelation the relation object.
	 */
Qiang Xue committed
514
	public function hasMany($class, $link)
Qiang Xue committed
515
	{
516
		return $this->createActiveRelation([
517
			'modelClass' => $class,
Qiang Xue committed
518 519 520
			'primaryModel' => $this,
			'link' => $link,
			'multiple' => true,
Alexander Makarov committed
521
		]);
Qiang Xue committed
522 523
	}

524 525 526 527 528 529 530 531 532 533 534 535
	/**
	 * 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.
	 */
	protected function createActiveRelation($config = [])
	{
		return new ActiveRelation($config);
	}

Qiang Xue committed
536
	/**
Qiang Xue committed
537 538
	 * Populates the named relation with the related records.
	 * Note that this method does not check if the relation exists or not.
Carsten Brandt committed
539
	 * @param string $name the relation name (case-sensitive)
Qiang Xue committed
540
	 * @param ActiveRecord|array|null the related records to be populated into the relation.
Qiang Xue committed
541
	 */
Qiang Xue committed
542
	public function populateRelation($name, $records)
Qiang Xue committed
543
	{
544
		$this->_related[$name] = $records;
Qiang Xue committed
545 546
	}

547 548
	/**
	 * Check whether the named relation has been populated with records.
Carsten Brandt committed
549
	 * @param string $name the relation name (case-sensitive)
550 551 552 553
	 * @return bool whether relation has been populated with records.
	 */
	public function isRelationPopulated($name)
	{
554
		return array_key_exists($name, $this->_related);
555 556 557
	}

	/**
Carsten Brandt committed
558 559
	 * Returns all populated relations.
	 * @return array an array of relation data indexed by relation names.
560 561 562
	 */
	public function getPopulatedRelations()
	{
563
		return $this->_related;
Qiang Xue committed
564 565
	}

Qiang Xue committed
566 567
	/**
	 * Returns the list of all attribute names of the model.
Qiang Xue committed
568
	 * The default implementation will return all column names of the table associated with this AR class.
Qiang Xue committed
569 570
	 * @return array list of attribute names.
	 */
571
	public function attributes()
Qiang Xue committed
572
	{
Qiang Xue committed
573
		return array_keys($this->getTableSchema()->columns);
574 575
	}

576 577 578 579 580 581 582 583 584 585
	/**
	 * Returns a value indicating whether the model has an attribute with the specified name.
	 * @param string $name the name of the attribute
	 * @return boolean whether the model has an attribute with the specified name.
	 */
	public function hasAttribute($name)
	{
		return isset($this->_attributes[$name]) || isset($this->getTableSchema()->columns[$name]);
	}

w  
Qiang Xue committed
586 587 588 589 590 591
	/**
	 * Returns the named attribute value.
	 * If this record is the result of a query and the attribute is not loaded,
	 * null will be returned.
	 * @param string $name the attribute name
	 * @return mixed the attribute value. Null if the attribute is not set or does not exist.
592
	 * @see hasAttribute()
w  
Qiang Xue committed
593 594 595
	 */
	public function getAttribute($name)
	{
Qiang Xue committed
596
		return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
w  
Qiang Xue committed
597 598 599 600 601 602
	}

	/**
	 * Sets the named attribute value.
	 * @param string $name the attribute name
	 * @param mixed $value the attribute value.
603
	 * @throws InvalidParamException if the named attribute does not exist.
604
	 * @see hasAttribute()
w  
Qiang Xue committed
605 606 607
	 */
	public function setAttribute($name, $value)
	{
608
		if ($this->hasAttribute($name)) {
609 610 611 612
			$this->_attributes[$name] = $value;
		} else {
			throw new InvalidParamException(get_class($this) . ' has no attribute named "' . $name . '".');
		}
w  
Qiang Xue committed
613 614
	}

Qiang Xue committed
615 616 617 618 619 620
	/**
	 * Returns the old attribute values.
	 * @return array the old attribute values (name-value pairs)
	 */
	public function getOldAttributes()
	{
Alexander Makarov committed
621
		return $this->_oldAttributes === null ? [] : $this->_oldAttributes;
Qiang Xue committed
622 623 624 625 626 627 628 629 630 631 632 633
	}

	/**
	 * Sets the old attribute values.
	 * All existing old attribute values will be discarded.
	 * @param array $values old attribute values to be set.
	 */
	public function setOldAttributes($values)
	{
		$this->_oldAttributes = $values;
	}

Qiang Xue committed
634 635 636 637 638 639 640
	/**
	 * Returns the old value of the named attribute.
	 * If this record is the result of a query and the attribute is not loaded,
	 * null will be returned.
	 * @param string $name the attribute name
	 * @return mixed the old attribute value. Null if the attribute is not loaded before
	 * or does not exist.
641
	 * @see hasAttribute()
Qiang Xue committed
642 643 644 645 646 647 648 649 650 651
	 */
	public function getOldAttribute($name)
	{
		return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
	}

	/**
	 * Sets the old value of the named attribute.
	 * @param string $name the attribute name
	 * @param mixed $value the old attribute value.
652
	 * @throws InvalidParamException if the named attribute does not exist.
653
	 * @see hasAttribute()
Qiang Xue committed
654 655 656
	 */
	public function setOldAttribute($name, $value)
	{
657
		if (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name)) {
658 659 660 661
			$this->_oldAttributes[$name] = $value;
		} else {
			throw new InvalidParamException(get_class($this) . ' has no attribute named "' . $name . '".');
		}
Qiang Xue committed
662 663 664 665 666 667 668 669 670
	}

	/**
	 * Returns a value indicating whether the named attribute has been changed.
	 * @param string $name the name of the attribute
	 * @return boolean whether the attribute has been changed
	 */
	public function isAttributeChanged($name)
	{
671 672
		if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
			return $this->_attributes[$name] !== $this->_oldAttributes[$name];
Qiang Xue committed
673
		} else {
Qiang Xue committed
674
			return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
Qiang Xue committed
675 676 677
		}
	}

Qiang Xue committed
678 679 680 681 682 683
	/**
	 * Returns the attribute values that have been modified since they are loaded or saved most recently.
	 * @param string[]|null $names the names of the attributes whose values may be returned if they are
	 * changed recently. If null, [[attributes()]] will be used.
	 * @return array the changed attribute values (name-value pairs)
	 */
Qiang Xue committed
684
	public function getDirtyAttributes($names = null)
Qiang Xue committed
685 686
	{
		if ($names === null) {
687
			$names = $this->attributes();
Qiang Xue committed
688 689
		}
		$names = array_flip($names);
Alexander Makarov committed
690
		$attributes = [];
Qiang Xue committed
691
		if ($this->_oldAttributes === null) {
Qiang Xue committed
692 693 694 695 696 697 698 699 700 701
			foreach ($this->_attributes as $name => $value) {
				if (isset($names[$name])) {
					$attributes[$name] = $value;
				}
			}
		} else {
			foreach ($this->_attributes as $name => $value) {
				if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $value !== $this->_oldAttributes[$name])) {
					$attributes[$name] = $value;
				}
w  
Qiang Xue committed
702
			}
Qiang Xue committed
703
		}
Qiang Xue committed
704
		return $attributes;
w  
Qiang Xue committed
705 706 707 708 709
	}

	/**
	 * Saves the current record.
	 *
Qiang Xue committed
710 711 712 713
	 * This method will call [[insert()]] when [[isNewRecord]] is true, or [[update()]]
	 * when [[isNewRecord]] is false.
	 *
	 * For example, to save a customer record:
w  
Qiang Xue committed
714
	 *
Qiang Xue committed
715 716 717 718 719 720
	 * ~~~
	 * $customer = new Customer;  // or $customer = Customer::find($id);
	 * $customer->name = $name;
	 * $customer->email = $email;
	 * $customer->save();
	 * ~~~
w  
Qiang Xue committed
721 722 723 724 725 726 727 728 729 730
	 *
	 *
	 * @param boolean $runValidation whether to perform validation before saving the record.
	 * If the validation fails, the record will not be saved to database.
	 * @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 saving succeeds
	 */
	public function save($runValidation = true, $attributes = null)
	{
731 732 733 734 735
		if ($this->getIsNewRecord()) {
			return $this->insert($runValidation, $attributes);
		} else {
			return $this->update($runValidation, $attributes) !== false;
		}
Qiang Xue committed
736 737 738
	}

	/**
Qiang Xue committed
739 740 741 742 743 744
	 * 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;
745 746
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
Qiang Xue committed
747
	 *    rest of the steps;
748 749
	 * 4. insert the record into database. If this fails, it will skip the rest of the steps;
	 * 5. call [[afterSave()]];
Qiang Xue committed
750
	 *
751
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
Qiang Xue committed
752 753
	 * [[EVENT_BEFORE_INSERT]], [[EVENT_AFTER_INSERT]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
Qiang Xue committed
754 755 756 757
	 *
	 * Only the [[changedAttributes|changed attribute values]] will be inserted into database.
	 *
	 * If the table's primary key is auto-incremental and is null during insertion,
Qiang Xue committed
758
	 * it will be populated with the actual value after insertion.
Qiang Xue committed
759 760 761 762 763 764 765 766 767 768 769 770
	 *
	 * 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
771 772 773
	 * @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.
774
	 * @throws \Exception in case insert failed.
Qiang Xue committed
775
	 */
Qiang Xue committed
776
	public function insert($runValidation = true, $attributes = null)
Qiang Xue committed
777
	{
778 779 780 781
		if ($runValidation && !$this->validate($attributes)) {
			return false;
		}
		$db = static::getDb();
Qiang Xue committed
782 783 784 785
		if ($this->isTransactional(self::OP_INSERT) && $db->getTransaction() === null) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->insertInternal($attributes);
resurtm committed
786
				if ($result === false) {
787 788 789 790
					$transaction->rollback();
				} else {
					$transaction->commit();
				}
Qiang Xue committed
791
			} catch (\Exception $e) {
792
				$transaction->rollback();
Qiang Xue committed
793
				throw $e;
794
			}
Qiang Xue committed
795 796
		} else {
			$result = $this->insertInternal($attributes);
797 798 799 800 801 802 803
		}
		return $result;
	}

	/**
	 * @see ActiveRecord::insert()
	 */
resurtm committed
804
	private function insertInternal($attributes = null)
805 806
	{
		if (!$this->beforeSave(true)) {
Qiang Xue committed
807 808
			return false;
		}
809 810 811 812
		$values = $this->getDirtyAttributes($attributes);
		if (empty($values)) {
			foreach ($this->primaryKey() as $key) {
				$values[$key] = isset($this->_attributes[$key]) ? $this->_attributes[$key] : null;
Qiang Xue committed
813
			}
814 815 816
		}
		$db = static::getDb();
		$command = $db->createCommand()->insert($this->tableName(), $values);
817 818 819 820 821 822 823 824 825
		if (!$command->execute()) {
			return false;
		}
		$table = $this->getTableSchema();
		if ($table->sequenceName !== null) {
			foreach ($table->primaryKey as $name) {
				if (!isset($this->_attributes[$name])) {
					$this->_oldAttributes[$name] = $this->_attributes[$name] = $db->getLastInsertID($table->sequenceName);
					break;
Qiang Xue committed
826 827 828
				}
			}
		}
829 830 831 832 833
		foreach ($values as $name => $value) {
			$this->_oldAttributes[$name] = $value;
		}
		$this->afterSave(true);
		return true;
Qiang Xue committed
834 835 836
	}

	/**
Qiang Xue committed
837 838 839 840 841 842
	 * 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;
843 844
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
Qiang Xue committed
845
	 *    rest of the steps;
846 847
	 * 4. save the record into database. If this fails, it will skip the rest of the steps;
	 * 5. call [[afterSave()]];
Qiang Xue committed
848
	 *
849
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
Qiang Xue committed
850 851
	 * [[EVENT_BEFORE_UPDATE]], [[EVENT_AFTER_UPDATE]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
Qiang Xue committed
852 853 854 855 856 857 858 859 860 861 862 863
	 *
	 * 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();
	 * ~~~
	 *
864 865 866 867 868 869 870 871 872 873 874 875
	 * 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
876 877
	 * @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
878 879
	 * @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.
880 881
	 * @return integer|boolean the number of rows affected, or false if validation fails
	 * or [[beforeSave()]] stops the updating process.
882
	 * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
883
	 * being updated is outdated.
884
	 * @throws \Exception in case update failed.
Qiang Xue committed
885
	 */
Qiang Xue committed
886
	public function update($runValidation = true, $attributes = null)
Qiang Xue committed
887
	{
888
		if ($runValidation && !$this->validate($attributes)) {
Qiang Xue committed
889 890
			return false;
		}
891
		$db = static::getDb();
Qiang Xue committed
892 893 894 895
		if ($this->isTransactional(self::OP_UPDATE) && $db->getTransaction() === null) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->updateInternal($attributes);
resurtm committed
896
				if ($result === false) {
897 898 899
					$transaction->rollback();
				} else {
					$transaction->commit();
900
				}
Qiang Xue committed
901
			} catch (\Exception $e) {
902
				$transaction->rollback();
Qiang Xue committed
903
				throw $e;
904
			}
Qiang Xue committed
905 906
		} else {
			$result = $this->updateInternal($attributes);
907 908 909
		}
		return $result;
	}
910

911 912 913 914
	/**
	 * @see CActiveRecord::update()
	 * @throws StaleObjectException
	 */
resurtm committed
915
	private function updateInternal($attributes = null)
916 917 918 919 920 921
	{
		if (!$this->beforeSave(false)) {
			return false;
		}
		$values = $this->getDirtyAttributes($attributes);
		if (empty($values)) {
Qiang Xue committed
922
			$this->afterSave(false);
923 924 925 926 927 928 929
			return 0;
		}
		$condition = $this->getOldPrimaryKey(true);
		$lock = $this->optimisticLock();
		if ($lock !== null) {
			if (!isset($values[$lock])) {
				$values[$lock] = $this->$lock + 1;
Qiang Xue committed
930
			}
931 932 933 934 935
			$condition[$lock] = $this->$lock;
		}
		// We do not check the return value of updateAll() because it's possible
		// that the UPDATE statement doesn't change anything and thus returns 0.
		$rows = $this->updateAll($values, $condition);
936

937 938 939 940 941 942
		if ($lock !== null && !$rows) {
			throw new StaleObjectException('The object being updated is outdated.');
		}

		foreach ($values as $name => $value) {
			$this->_oldAttributes[$name] = $this->_attributes[$name];
Qiang Xue committed
943
		}
944 945
		$this->afterSave(false);
		return $rows;
Qiang Xue committed
946 947 948
	}

	/**
Qiang Xue committed
949
	 * Updates one or several counter columns for the current AR object.
Qiang Xue committed
950 951 952 953 954 955
	 * Note that this method differs from [[updateAllCounters()]] in that it only
	 * saves counters for the current AR object.
	 *
	 * An example usage is as follows:
	 *
	 * ~~~
Qiang Xue committed
956
	 * $post = Post::find($id);
Alexander Makarov committed
957
	 * $post->updateCounters(['view_count' => 1]);
Qiang Xue committed
958 959 960
	 * ~~~
	 *
	 * @param array $counters the counters to be updated (attribute name => increment value)
Qiang Xue committed
961
	 * Use negative values if you want to decrement the counters.
Qiang Xue committed
962 963 964 965 966
	 * @return boolean whether the saving is successful
	 * @see updateAllCounters()
	 */
	public function updateCounters($counters)
	{
Qiang Xue committed
967 968 969 970 971 972 973 974
		if ($this->updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
			foreach ($counters as $name => $value) {
				$this->_attributes[$name] += $value;
				$this->_oldAttributes[$name] = $this->_attributes[$name];
			}
			return true;
		} else {
			return false;
Qiang Xue committed
975 976 977 978
		}
	}

	/**
Qiang Xue committed
979 980 981 982 983 984 985 986 987
	 * 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
988
	 * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
Qiang Xue committed
989 990
	 * will be raised by the corresponding methods.
	 *
991 992
	 * @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.
993
	 * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
994
	 * being deleted is outdated.
995
	 * @throws \Exception in case delete failed.
Qiang Xue committed
996 997 998
	 */
	public function delete()
	{
999
		$db = static::getDb();
1000
		$transaction = $this->isTransactional(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
1001 1002 1003 1004 1005 1006 1007
		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
1008
				if ($lock !== null) {
1009 1010 1011
					$condition[$lock] = $this->$lock;
				}
				$result = $this->deleteAll($condition);
resurtm committed
1012
				if ($lock !== null && !$result) {
1013 1014 1015 1016
					throw new StaleObjectException('The object being deleted is outdated.');
				}
				$this->_oldAttributes = null;
				$this->afterDelete();
1017
			}
resurtm committed
1018 1019
			if ($transaction !== null) {
				if ($result === false) {
1020 1021 1022 1023
					$transaction->rollback();
				} else {
					$transaction->commit();
				}
1024
			}
1025
		} catch (\Exception $e) {
resurtm committed
1026
			if ($transaction !== null) {
1027 1028 1029
				$transaction->rollback();
			}
			throw $e;
Qiang Xue committed
1030
		}
1031
		return $result;
w  
Qiang Xue committed
1032 1033 1034
	}

	/**
Qiang Xue committed
1035
	 * Returns a value indicating whether the current record is new.
Qiang Xue committed
1036
	 * @return boolean whether the record is new and should be inserted when calling [[save()]].
w  
Qiang Xue committed
1037 1038 1039
	 */
	public function getIsNewRecord()
	{
Qiang Xue committed
1040
		return $this->_oldAttributes === null;
w  
Qiang Xue committed
1041 1042
	}

Qiang Xue committed
1043 1044 1045
	/**
	 * Sets the value indicating whether the record is new.
	 * @param boolean $value whether the record is new and should be inserted when calling [[save()]].
1046
	 * @see getIsNewRecord()
Qiang Xue committed
1047 1048 1049 1050 1051 1052
	 */
	public function setIsNewRecord($value)
	{
		$this->_oldAttributes = $value ? null : $this->_attributes;
	}

1053 1054 1055
	/**
	 * Initializes the object.
	 * This method is called at the end of the constructor.
Qiang Xue committed
1056
	 * The default implementation will trigger an [[EVENT_INIT]] event.
1057 1058 1059 1060 1061 1062
	 * If you override this method, make sure you call the parent implementation at the end
	 * to ensure triggering of the event.
	 */
	public function init()
	{
		parent::init();
1063
		$this->trigger(self::EVENT_INIT);
1064 1065 1066 1067
	}

	/**
	 * This method is called when the AR object is created and populated with the query result.
Qiang Xue committed
1068
	 * The default implementation will trigger an [[EVENT_AFTER_FIND]] event.
1069 1070 1071 1072 1073
	 * When overriding this method, make sure you call the parent implementation to ensure the
	 * event is triggered.
	 */
	public function afterFind()
	{
1074
		$this->trigger(self::EVENT_AFTER_FIND);
1075 1076
	}

Qiang Xue committed
1077 1078
	/**
	 * This method is called at the beginning of inserting or updating a record.
Qiang Xue committed
1079 1080
	 * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is true,
	 * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is false.
Qiang Xue committed
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
	 * When overriding this method, make sure you call the parent implementation like the following:
	 *
	 * ~~~
	 * public function beforeSave($insert)
	 * {
	 *     if (parent::beforeSave($insert)) {
	 *         // ...custom code here...
	 *         return true;
	 *     } else {
	 *         return false;
	 *     }
	 * }
	 * ~~~
	 *
	 * @param boolean $insert whether this method called while inserting a record.
	 * If false, it means the method is called while updating a record.
	 * @return boolean whether the insertion or updating should continue.
	 * If false, the insertion or updating will be cancelled.
	 */
Qiang Xue committed
1100
	public function beforeSave($insert)
w  
Qiang Xue committed
1101
	{
Qiang Xue committed
1102
		$event = new ModelEvent;
1103
		$this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
Qiang Xue committed
1104
		return $event->isValid;
w  
Qiang Xue committed
1105 1106
	}

Qiang Xue committed
1107 1108
	/**
	 * This method is called at the end of inserting or updating a record.
Qiang Xue committed
1109 1110
	 * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is true,
	 * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is false.
Qiang Xue committed
1111 1112 1113 1114 1115
	 * When overriding this method, make sure you call the parent implementation so that
	 * the event is triggered.
	 * @param boolean $insert whether this method called while inserting a record.
	 * If false, it means the method is called while updating a record.
	 */
Qiang Xue committed
1116
	public function afterSave($insert)
w  
Qiang Xue committed
1117
	{
1118
		$this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE);
w  
Qiang Xue committed
1119 1120 1121 1122
	}

	/**
	 * This method is invoked before deleting a record.
Qiang Xue committed
1123
	 * The default implementation raises the [[EVENT_BEFORE_DELETE]] event.
Qiang Xue committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
	 * When overriding this method, make sure you call the parent implementation like the following:
	 *
	 * ~~~
	 * public function beforeDelete()
	 * {
	 *     if (parent::beforeDelete()) {
	 *         // ...custom code here...
	 *         return true;
	 *     } else {
	 *         return false;
	 *     }
	 * }
	 * ~~~
	 *
w  
Qiang Xue committed
1138 1139
	 * @return boolean whether the record should be deleted. Defaults to true.
	 */
Qiang Xue committed
1140
	public function beforeDelete()
w  
Qiang Xue committed
1141
	{
Qiang Xue committed
1142
		$event = new ModelEvent;
1143
		$this->trigger(self::EVENT_BEFORE_DELETE, $event);
Qiang Xue committed
1144
		return $event->isValid;
w  
Qiang Xue committed
1145 1146 1147 1148
	}

	/**
	 * This method is invoked after deleting a record.
Qiang Xue committed
1149
	 * The default implementation raises the [[EVENT_AFTER_DELETE]] event.
w  
Qiang Xue committed
1150 1151 1152
	 * You may override this method to do postprocessing after the record is deleted.
	 * Make sure you call the parent implementation so that the event is raised properly.
	 */
Qiang Xue committed
1153
	public function afterDelete()
w  
Qiang Xue committed
1154
	{
1155
		$this->trigger(self::EVENT_AFTER_DELETE);
w  
Qiang Xue committed
1156 1157 1158
	}

	/**
Qiang Xue committed
1159
	 * Repopulates this active record with the latest data.
Qiang Xue committed
1160
	 * @return boolean whether the row still exists in the database. If true, the latest data
1161
	 * will be populated to this active record. Otherwise, this record will remain unchanged.
w  
Qiang Xue committed
1162
	 */
1163
	public function refresh()
w  
Qiang Xue committed
1164
	{
Qiang Xue committed
1165
		$record = $this->find($this->getPrimaryKey(true));
Qiang Xue committed
1166 1167 1168
		if ($record === null) {
			return false;
		}
1169 1170
		foreach ($this->attributes() as $name) {
			$this->_attributes[$name] = $record->_attributes[$name];
w  
Qiang Xue committed
1171
		}
1172
		$this->_oldAttributes = $this->_attributes;
1173
		$this->_related = [];
Qiang Xue committed
1174
		return true;
w  
Qiang Xue committed
1175 1176 1177
	}

	/**
Qiang Xue committed
1178 1179
	 * 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.
Qiang Xue committed
1180
	 * @param ActiveRecord $record record to compare to
Qiang Xue committed
1181
	 * @return boolean whether the two active records refer to the same row in the same database table.
w  
Qiang Xue committed
1182
	 */
Qiang Xue committed
1183
	public function equals($record)
w  
Qiang Xue committed
1184
	{
Qiang Xue committed
1185
		return $this->tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
w  
Qiang Xue committed
1186 1187 1188
	}

	/**
Qiang Xue committed
1189
	 * Returns the primary key value(s).
Qiang Xue committed
1190
	 * @param boolean $asArray whether to return the primary key value as an array. If true,
Qiang Xue committed
1191
	 * the return value will be an array with column names as keys and column values as values.
1192
	 * Note that for composite primary keys, an array will always be returned regardless of this parameter value.
resurtm committed
1193
	 * @return mixed the primary key value. An array (column name => column value) is returned if the primary key
Qiang Xue committed
1194 1195
	 * is composite or `$asArray` is true. A string is returned otherwise (null will be returned if
	 * the key value is null).
w  
Qiang Xue committed
1196
	 */
Qiang Xue committed
1197
	public function getPrimaryKey($asArray = false)
w  
Qiang Xue committed
1198
	{
Qiang Xue committed
1199 1200 1201
		$keys = $this->primaryKey();
		if (count($keys) === 1 && !$asArray) {
			return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
Qiang Xue committed
1202
		} else {
Alexander Makarov committed
1203
			$values = [];
Qiang Xue committed
1204
			foreach ($keys as $name) {
Qiang Xue committed
1205
				$values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
Qiang Xue committed
1206 1207
			}
			return $values;
w  
Qiang Xue committed
1208 1209 1210 1211
		}
	}

	/**
Qiang Xue committed
1212
	 * Returns the old primary key value(s).
Qiang Xue committed
1213 1214 1215
	 * This refers to the primary key value that is populated into the record
	 * after executing a find method (e.g. find(), findAll()).
	 * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
Qiang Xue committed
1216 1217
	 * @param boolean $asArray whether to return the primary key value as an array. If true,
	 * the return value will be an array with column name as key and column value as value.
Qiang Xue committed
1218
	 * If this is false (default), a scalar value will be returned for non-composite primary key.
resurtm committed
1219
	 * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key
Qiang Xue committed
1220 1221
	 * is composite or `$asArray` is true. A string is returned otherwise (null will be returned if
	 * the key value is null).
w  
Qiang Xue committed
1222
	 */
Qiang Xue committed
1223
	public function getOldPrimaryKey($asArray = false)
w  
Qiang Xue committed
1224
	{
Qiang Xue committed
1225 1226 1227
		$keys = $this->primaryKey();
		if (count($keys) === 1 && !$asArray) {
			return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
Qiang Xue committed
1228
		} else {
Alexander Makarov committed
1229
			$values = [];
Qiang Xue committed
1230
			foreach ($keys as $name) {
Qiang Xue committed
1231 1232 1233 1234
				$values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
			}
			return $values;
		}
w  
Qiang Xue committed
1235 1236 1237
	}

	/**
Qiang Xue committed
1238
	 * Creates an active record object using a row of data.
Qiang Xue committed
1239
	 * This method is called by [[ActiveQuery]] to populate the query results
1240
	 * into Active Records. It is not meant to be used to create new records.
Qiang Xue committed
1241 1242
	 * @param array $row attribute values (name => value)
	 * @return ActiveRecord the newly created active record.
w  
Qiang Xue committed
1243
	 */
Qiang Xue committed
1244
	public static function create($row)
w  
Qiang Xue committed
1245
	{
Qiang Xue committed
1246
		$record = static::instantiate($row);
1247
		$columns = static::getTableSchema()->columns;
Qiang Xue committed
1248
		foreach ($row as $name => $value) {
Qiang Xue committed
1249
			if (isset($columns[$name])) {
Qiang Xue committed
1250
				$record->_attributes[$name] = $value;
Qiang Xue committed
1251
			} else {
Qiang Xue committed
1252
				$record->$name = $value;
w  
Qiang Xue committed
1253 1254
			}
		}
Qiang Xue committed
1255
		$record->_oldAttributes = $record->_attributes;
1256
		$record->afterFind();
Qiang Xue committed
1257
		return $record;
w  
Qiang Xue committed
1258 1259 1260 1261
	}

	/**
	 * Creates an active record instance.
Qiang Xue committed
1262
	 * This method is called by [[create()]].
w  
Qiang Xue committed
1263
	 * You may override this method if the instance being created
Qiang Xue committed
1264
	 * depends on the row data to be populated into the record.
w  
Qiang Xue committed
1265 1266
	 * For example, by creating a record based on the value of a column,
	 * you may implement the so-called single-table inheritance mapping.
Qiang Xue committed
1267 1268
	 * @param array $row row data to be populated into the record.
	 * @return ActiveRecord the newly created active record
w  
Qiang Xue committed
1269
	 */
Qiang Xue committed
1270
	public static function instantiate($row)
w  
Qiang Xue committed
1271
	{
Qiang Xue committed
1272
		return new static;
w  
Qiang Xue committed
1273 1274 1275 1276 1277 1278
	}

	/**
	 * Returns whether there is an element at the specified offset.
	 * This method is required by the interface ArrayAccess.
	 * @param mixed $offset the offset to check on
Qiang Xue committed
1279
	 * @return boolean whether there is an element at the specified offset.
w  
Qiang Xue committed
1280 1281 1282 1283 1284
	 */
	public function offsetExists($offset)
	{
		return $this->__isset($offset);
	}
Qiang Xue committed
1285

Qiang Xue committed
1286
	/**
Qiang Xue committed
1287 1288 1289 1290 1291
	 * Returns the relation object with the specified name.
	 * A relation is defined by a getter method which returns an [[ActiveRelation]] object.
	 * It can be declared in either the Active Record class itself or one of its behaviors.
	 * @param string $name the relation name
	 * @return ActiveRelation the relation object
Qiang Xue committed
1292
	 * @throws InvalidParamException if the named relation does not exist.
Qiang Xue committed
1293 1294 1295 1296 1297 1298
	 */
	public function getRelation($name)
	{
		$getter = 'get' . $name;
		try {
			$relation = $this->$getter();
1299
			if ($relation instanceof ActiveRelationInterface) {
Qiang Xue committed
1300
				return $relation;
1301 1302
			} else {
				return null;
Qiang Xue committed
1303
			}
Qiang Xue committed
1304
		} catch (UnknownMethodException $e) {
1305
			throw new InvalidParamException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
Qiang Xue committed
1306 1307 1308
		}
	}

Qiang Xue committed
1309
	/**
Qiang Xue committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
	 * Establishes the relationship between two models.
	 *
	 * The relationship is established by setting the foreign key value(s) in one model
	 * to be the corresponding primary key value(s) in the other model.
	 * The model with the foreign key will be saved into database without performing validation.
	 *
	 * If the relationship involves a pivot table, a new row will be inserted into the
	 * pivot table which contains the primary key values from both models.
	 *
	 * Note that this method requires that the primary key value is not null.
	 *
1321
	 * @param string $name the case sensitive name of the relationship
Qiang Xue committed
1322 1323 1324 1325
	 * @param ActiveRecord $model the model to be linked with the current one.
	 * @param array $extraColumns additional column values to be saved into the pivot table.
	 * This parameter is only meaningful for a relationship involving a pivot table
	 * (i.e., a relation set with `[[ActiveRelation::via()]]` or `[[ActiveRelation::viaTable()]]`.)
Qiang Xue committed
1326
	 * @throws InvalidCallException if the method is unable to link two models.
Qiang Xue committed
1327
	 */
Alexander Makarov committed
1328
	public function link($name, $model, $extraColumns = [])
Qiang Xue committed
1329
	{
1330 1331 1332
		$relation = $this->getRelation($name);

		if ($relation->via !== null) {
Qiang Xue committed
1333 1334 1335
			if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
				throw new InvalidCallException('Unable to link models: both models must NOT be newly created.');
			}
1336
			if (is_array($relation->via)) {
slavcodev committed
1337
				/** @var ActiveRelation $viaRelation */
Qiang Xue committed
1338
				list($viaName, $viaRelation) = $relation->via;
slavcodev committed
1339
				/** @var ActiveRecord $viaClass */
Qiang Xue committed
1340
				$viaClass = $viaRelation->modelClass;
1341
				$viaTable = $viaClass::tableName();
Qiang Xue committed
1342
				// unset $viaName so that it can be reloaded to reflect the change
1343
				unset($this->_related[$viaName]);
1344
			} else {
Qiang Xue committed
1345
				$viaRelation = $relation->via;
1346 1347
				$viaTable = reset($relation->via->from);
			}
Alexander Makarov committed
1348
			$columns = [];
Qiang Xue committed
1349
			foreach ($viaRelation->link as $a => $b) {
1350 1351 1352 1353 1354
				$columns[$a] = $this->$b;
			}
			foreach ($relation->link as $a => $b) {
				$columns[$b] = $model->$a;
			}
Qiang Xue committed
1355
			foreach ($extraColumns as $k => $v) {
1356 1357
				$columns[$k] = $v;
			}
Qiang Xue committed
1358
			static::getDb()->createCommand()
Qiang Xue committed
1359 1360 1361 1362 1363 1364
				->insert($viaTable, $columns)->execute();
		} else {
			$p1 = $model->isPrimaryKey(array_keys($relation->link));
			$p2 = $this->isPrimaryKey(array_values($relation->link));
			if ($p1 && $p2) {
				if ($this->getIsNewRecord() && $model->getIsNewRecord()) {
Qiang Xue committed
1365
					throw new InvalidCallException('Unable to link models: both models are newly created.');
Qiang Xue committed
1366 1367
				} elseif ($this->getIsNewRecord()) {
					$this->bindModels(array_flip($relation->link), $this, $model);
Qiang Xue committed
1368
				} else {
Qiang Xue committed
1369
					$this->bindModels($relation->link, $model, $this);
1370
				}
Qiang Xue committed
1371 1372 1373 1374
			} elseif ($p1) {
				$this->bindModels(array_flip($relation->link), $this, $model);
			} elseif ($p2) {
				$this->bindModels($relation->link, $model, $this);
1375
			} else {
Qiang Xue committed
1376
				throw new InvalidCallException('Unable to link models: the link does not involve any primary key.');
1377 1378
			}
		}
Qiang Xue committed
1379

Qiang Xue committed
1380
		// update lazily loaded related objects
Qiang Xue committed
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
		if (!$relation->multiple) {
			$this->_related[$name] = $model;
		} elseif (isset($this->_related[$name])) {
			if ($relation->indexBy !== null) {
				$indexBy = $relation->indexBy;
				$this->_related[$name][$model->$indexBy] = $model;
			} else {
				$this->_related[$name][] = $model;
			}
		}
1391 1392 1393
	}

	/**
Qiang Xue committed
1394 1395 1396 1397 1398
	 * Destroys the relationship between two models.
	 *
	 * The model with the foreign key of the relationship will be deleted if `$delete` is true.
	 * Otherwise, the foreign key will be set null and the model will be saved without validation.
	 *
1399
	 * @param string $name the case sensitive name of the relationship.
Qiang Xue committed
1400
	 * @param ActiveRecord $model the model to be unlinked from the current one.
Qiang Xue committed
1401 1402
	 * @param boolean $delete whether to delete the model that contains the foreign key.
	 * If false, the model's foreign key will be set null and saved.
Qiang Xue committed
1403
	 * If true, the model containing the foreign key will be deleted.
Qiang Xue committed
1404
	 * @throws InvalidCallException if the models cannot be unlinked
1405
	 */
Qiang Xue committed
1406
	public function unlink($name, $model, $delete = false)
1407 1408 1409 1410 1411
	{
		$relation = $this->getRelation($name);

		if ($relation->via !== null) {
			if (is_array($relation->via)) {
slavcodev committed
1412
				/** @var ActiveRelation $viaRelation */
Qiang Xue committed
1413
				list($viaName, $viaRelation) = $relation->via;
slavcodev committed
1414
				/** @var ActiveRecord $viaClass */
Qiang Xue committed
1415
				$viaClass = $viaRelation->modelClass;
1416
				$viaTable = $viaClass::tableName();
1417
				unset($this->_related[$viaName]);
1418
			} else {
Qiang Xue committed
1419
				$viaRelation = $relation->via;
1420 1421
				$viaTable = reset($relation->via->from);
			}
Alexander Makarov committed
1422
			$columns = [];
Qiang Xue committed
1423
			foreach ($viaRelation->link as $a => $b) {
1424 1425 1426 1427 1428
				$columns[$a] = $this->$b;
			}
			foreach ($relation->link as $a => $b) {
				$columns[$b] = $model->$a;
			}
Qiang Xue committed
1429
			$command = static::getDb()->createCommand();
Qiang Xue committed
1430 1431 1432
			if ($delete) {
				$command->delete($viaTable, $columns)->execute();
			} else {
Alexander Makarov committed
1433
				$nulls = [];
Qiang Xue committed
1434 1435 1436 1437
				foreach (array_keys($columns) as $a) {
					$nulls[$a] = null;
				}
				$command->update($viaTable, $nulls, $columns)->execute();
1438 1439
			}
		} else {
Qiang Xue committed
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
			$p1 = $model->isPrimaryKey(array_keys($relation->link));
			$p2 = $this->isPrimaryKey(array_values($relation->link));
			if ($p1 && $p2 || $p2) {
				foreach ($relation->link as $a => $b) {
					$model->$a = null;
				}
				$delete ? $model->delete() : $model->save(false);
			} elseif ($p1) {
				foreach ($relation->link as $b) {
					$this->$b = null;
				}
				$delete ? $this->delete() : $this->save(false);
			} else {
Qiang Xue committed
1453
				throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
Qiang Xue committed
1454
			}
1455
		}
Qiang Xue committed
1456 1457 1458 1459

		if (!$relation->multiple) {
			unset($this->_related[$name]);
		} elseif (isset($this->_related[$name])) {
slavcodev committed
1460
			/** @var ActiveRecord $b */
Qiang Xue committed
1461 1462 1463 1464 1465 1466
			foreach ($this->_related[$name] as $a => $b) {
				if ($model->getPrimaryKey() == $b->getPrimaryKey()) {
					unset($this->_related[$name][$a]);
				}
			}
		}
1467 1468 1469
	}

	/**
Qiang Xue committed
1470 1471 1472
	 * @param array $link
	 * @param ActiveRecord $foreignModel
	 * @param ActiveRecord $primaryModel
Qiang Xue committed
1473
	 * @throws InvalidCallException
1474
	 */
Qiang Xue committed
1475
	private function bindModels($link, $foreignModel, $primaryModel)
1476
	{
Qiang Xue committed
1477 1478 1479
		foreach ($link as $fk => $pk) {
			$value = $primaryModel->$pk;
			if ($value === null) {
Qiang Xue committed
1480
				throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.');
Qiang Xue committed
1481
			}
Qiang Xue committed
1482
			$foreignModel->$fk = $value;
Qiang Xue committed
1483
		}
Qiang Xue committed
1484 1485 1486 1487
		$foreignModel->save(false);
	}

	/**
1488 1489 1490
	 * Returns a value indicating whether the given set of attributes represents the primary key for this model
	 * @param array $keys the set of attributes to check
	 * @return boolean whether the given set of attributes represents the primary key for this model
Qiang Xue committed
1491
	 */
1492
	public static function isPrimaryKey($keys)
Qiang Xue committed
1493
	{
1494
		$pks = static::primaryKey();
Qiang Xue committed
1495 1496 1497 1498 1499
		foreach ($keys as $key) {
			if (!in_array($key, $pks, true)) {
				return false;
			}
		}
1500
		return count($keys) === count($pks);
Qiang Xue committed
1501
	}
1502 1503

	/**
1504 1505 1506
	 * 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]].
1507
	 */
1508
	public function isTransactional($operation)
1509 1510
	{
		$scenario = $this->getScenario();
1511 1512
		$transactions = $this->transactions();
		return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
1513
	}
w  
Qiang Xue committed
1514
}