ActiveRecord.php 23.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\sphinx;

use yii\base\InvalidConfigException;
11
use yii\base\NotSupportedException;
12
use yii\db\ActiveRelationInterface;
13
use yii\db\BaseActiveRecord;
14 15
use yii\db\StaleObjectException;
use yii\helpers\Inflector;
16
use Yii;
17
use yii\helpers\StringHelper;
18 19

/**
20 21
 * ActiveRecord is the base class for classes representing relational data in terms of objects.
 *
22 23 24
 * Warning: optimistic lock will NOT work in case of updating fields (not attributes) for the
 * runtime indexes!
 *
25 26 27 28
 * @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).
29 30 31
 * @property mixed $oldPrimaryKey The old primary key value. An array (column name => column value) is
 * returned if the primary key is composite. A string is returned otherwise (null will be returned if the key
 * value is null). This property is read-only.
32
 * @property array $relatedRecords An array of the populated related records indexed by relation names. This property is
33
 * read-only.
34 35 36 37 38
 * @property mixed $primaryKey The primary key value. An array (column name => column value) is returned if
 * the primary key is composite. A string is returned otherwise (null will be returned if the key value is null).
 * This property is read-only.
 * @property string $snippet Snippet value.
 * @property string $snippetSource Snippet source string. This property is read-only.
39 40 41 42
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
43
abstract class ActiveRecord extends BaseActiveRecord
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
{
	/**
	 * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
	 */
	const OP_INSERT = 0x01;
	/**
	 * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
	 */
	const OP_UPDATE = 0x02;
	/**
	 * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
	 */
	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;

63
	/**
64 65 66
	 * @var string current snippet value for this Active Record instance.
	 * It will be filled up automatically when instance found using [[Query::snippetCallback]]
	 * or [[ActiveQuery::snippetByModel()]].
67 68
	 */
	private $_snippet;
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

	/**
	 * Returns the Sphinx connection used by this AR class.
	 * By default, the "sphinx" application component is used as the Sphinx connection.
	 * You may override this method if you want to use a different Sphinx connection.
	 * @return Connection the Sphinx connection used by this AR class.
	 */
	public static function getDb()
	{
		return \Yii::$app->getComponent('sphinx');
	}

	/**
	 * 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:
	 *
	 * ~~~
92
	 * $customers = Article::findBySql("SELECT * FROM `idx_article` WHERE MATCH('development')")->all();
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
	 * ~~~
	 *
	 * @param string $sql the SQL statement to be executed
	 * @param array $params parameters to be bound to the SQL statement during execution.
	 * @return ActiveQuery the newly created [[ActiveQuery]] instance
	 */
	public static function findBySql($sql, $params = [])
	{
		$query = static::createQuery();
		$query->sql = $sql;
		return $query->params($params);
	}

	/**
	 * Updates the whole table using the provided attribute values and conditions.
108
	 * For example, to change the status to be 1 for all articles which status is 2:
109 110
	 *
	 * ~~~
111
	 * Article::updateAll(['status' => 1], 'status = 2');
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
	 * ~~~
	 *
	 * @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.
	 * Please refer to [[Query::where()]] on how to specify this parameter.
	 * @param array $params the parameters (name => value) to be bound to the query.
	 * @return integer the number of rows updated
	 */
	public static function updateAll($attributes, $condition = '', $params = [])
	{
		$command = static::getDb()->createCommand();
		$command->update(static::indexName(), $attributes, $condition, $params);
		return $command->execute();
	}

	/**
128
	 * Deletes rows in the index using the provided conditions.
129
	 *
130
	 * For example, to delete all articles whose status is 3:
131 132
	 *
	 * ~~~
133
	 * Article::deleteAll('status = 3');
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	 * ~~~
	 *
	 * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
	 * Please refer to [[Query::where()]] on how to specify this parameter.
	 * @param array $params the parameters (name => value) to be bound to the query.
	 * @return integer the number of rows deleted
	 */
	public static function deleteAll($condition = '', $params = [])
	{
		$command = static::getDb()->createCommand();
		$command->delete(static::indexName(), $condition, $params);
		return $command->execute();
	}

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

	/**
161 162 163 164 165
	 * Declares the name of the Sphinx index associated with this AR class.
	 * By default this method returns the class name as the index name by calling [[Inflector::camel2id()]].
	 * For example, 'Article' becomes 'article', and 'StockItem' becomes
	 * 'stock_item'. You may override this method if the index is not named after this convention.
	 * @return string the index name
166 167 168
	 */
	public static function indexName()
	{
169
		return Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
170 171 172
	}

	/**
173 174 175
	 * Returns the schema information of the Sphinx index associated with this AR class.
	 * @return IndexSchema the schema information of the Sphinx index associated with this AR class.
	 * @throws InvalidConfigException if the index for the AR class does not exist.
176 177 178 179 180 181 182 183 184 185 186 187 188
	 */
	public static function getIndexSchema()
	{
		$schema = static::getDb()->getIndexSchema(static::indexName());
		if ($schema !== null) {
			return $schema;
		} else {
			throw new InvalidConfigException("The index does not exist: " . static::indexName());
		}
	}

	/**
	 * Returns the primary key name for this AR class.
189 190 191 192 193 194
	 * The default implementation will return the primary key as declared
	 * in the Sphinx index, which is associated with this AR class.
	 *
	 * Note that an array should be returned even for a table with single primary key.
	 *
	 * @return string[] the primary keys of the associated Sphinx index.
195 196 197
	 */
	public static function primaryKey()
	{
198
		return [static::getIndexSchema()->primaryKey];
199 200
	}

201 202 203 204
	/**
	 * Builds a snippet from provided data and query, using specified index settings.
	 * @param string|array $source is the source data to extract a snippet from.
	 * It could be either a single string or array of strings.
205
	 * @param string $match the full-text query to build snippets for.
206 207 208 209
	 * @param array $options list of options in format: optionName => optionValue
	 * @return string|array built snippet in case "source" is a string, list of built snippets
	 * in case "source" is an array.
	 */
210
	public static function callSnippets($source, $match, $options = [])
211 212
	{
		$command = static::getDb()->createCommand();
213
		$command->callSnippets(static::indexName(), $source, $match, $options);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
		if (is_array($source)) {
			return $command->queryColumn();
		} else {
			return $command->queryScalar();
		}
	}

	/**
	 * Returns tokenized and normalized forms of the keywords, and, optionally, keyword statistics.
	 * @param string $text the text to break down to keywords.
	 * @param boolean $fetchStatistic whether to return document and hit occurrence statistics
	 * @return array keywords and statistics
	 */
	public static function callKeywords($text, $fetchStatistic = false)
	{
		$command = static::getDb()->createCommand();
		$command->callKeywords(static::indexName(), $text, $fetchStatistic);
		return $command->queryAll();
	}

	/**
	 * @param string $snippet
	 */
	public function setSnippet($snippet)
	{
		$this->_snippet = $snippet;
	}

	/**
243 244
	 * Returns current snippet value or generates new one from given match.
	 * @param string $match snippet source query
245 246 247
	 * @param array $options list of options in format: optionName => optionValue
	 * @return string snippet value
	 */
248
	public function getSnippet($match = null, $options = [])
249
	{
250 251
		if ($match !== null) {
			$this->_snippet = $this->fetchSnippet($match, $options);
252 253 254 255 256 257
		}
		return $this->_snippet;
	}

	/**
	 * Builds up the snippet value from the given query.
258
	 * @param string $match the full-text query to build snippets for.
259 260 261
	 * @param array $options list of options in format: optionName => optionValue
	 * @return string snippet value.
	 */
262
	protected function fetchSnippet($match, $options = [])
263
	{
264
		return static::callSnippets($this->getSnippetSource(), $match, $options);
265 266 267 268 269 270 271
	}

	/**
	 * Returns the string, which should be used as a source to create snippet for this
	 * Active Record instance.
	 * Child classes must implement this method to return the actual snippet source text.
	 * For example:
272
	 * ~~~
273 274 275 276
	 * public function getSnippetSource()
	 * {
	 *     return $this->snippetSourceRelation->content;
	 * }
277
	 * ~~~
278 279 280 281 282 283 284 285
	 * @return string snippet source string.
	 * @throws \yii\base\NotSupportedException if this is not supported by the Active Record class
	 */
	public function getSnippetSource()
	{
		throw new NotSupportedException($this->className() . ' does not provide snippet source.');
	}

286
	/**
287
	 * Declares which operations should be performed within a transaction in different scenarios.
288 289
	 * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
	 * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
290
	 * By default, these methods are NOT enclosed in a transaction.
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
	 *
	 * 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,
	 *
	 * ~~~
	 * return [
	 *     '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,
	 *
	 * ];
	 * ~~~
	 *
	 * 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()
	{
		return [];
	}

318 319 320 321 322 323 324
	/**
	 * Creates an [[ActiveRelationInterface]] 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 ActiveRelationInterface the newly created [[ActiveRelation]] instance.
	 */
325
	public static function createActiveRelation($config = [])
326
	{
327
		return new ActiveRelation($config);
328 329
	}

330 331 332 333 334
	/**
	 * 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.
	 */
335
	public function attributes()
336
	{
337
		return array_keys(static::getIndexSchema()->columns);
338 339 340
	}

	/**
341
	 * Inserts a row into the associated Sphinx index using the attribute values of this record.
342 343 344 345 346 347 348 349
	 *
	 * 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;
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
	 *    rest of the steps;
350
	 * 4. insert the record into index. If this fails, it will skip the rest of the steps;
351 352 353 354 355 356
	 * 5. call [[afterSave()]];
	 *
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
	 * [[EVENT_BEFORE_INSERT]], [[EVENT_AFTER_INSERT]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
	 *
357
	 * Only the [[changedAttributes|changed attribute values]] will be inserted.
358
	 *
359
	 * For example, to insert an article record:
360 361
	 *
	 * ~~~
362 363 364 365 366
	 * $article = new Article;
	 * $article->id = $id;
	 * $article->genre_id = $genreId;
	 * $article->content = $content;
	 * $article->insert();
367 368 369
	 * ~~~
	 *
	 * @param boolean $runValidation whether to perform validation before saving the record.
370
	 * If the validation fails, the record will not be inserted.
371
	 * @param array $attributes list of attributes that need to be saved. Defaults to null,
372
	 * meaning all attributes that are loaded from index will be saved.
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
	 * @return boolean whether the attributes are valid and the record is inserted successfully.
	 * @throws \Exception in case insert failed.
	 */
	public function insert($runValidation = true, $attributes = null)
	{
		if ($runValidation && !$this->validate($attributes)) {
			return false;
		}
		$db = static::getDb();
		if ($this->isTransactional(self::OP_INSERT) && $db->getTransaction() === null) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->insertInternal($attributes);
				if ($result === false) {
					$transaction->rollback();
				} else {
					$transaction->commit();
				}
			} catch (\Exception $e) {
				$transaction->rollback();
				throw $e;
			}
		} else {
			$result = $this->insertInternal($attributes);
		}
		return $result;
	}

	/**
	 * @see ActiveRecord::insert()
	 */
	private function insertInternal($attributes = null)
	{
		if (!$this->beforeSave(true)) {
			return false;
		}
		$values = $this->getDirtyAttributes($attributes);
		if (empty($values)) {
411 412
			foreach ($this->getPrimaryKey(true) as $key => $value) {
				$values[$key] = $value;
413
			}
414 415 416 417 418 419 420
		}
		$db = static::getDb();
		$command = $db->createCommand()->insert($this->indexName(), $values);
		if (!$command->execute()) {
			return false;
		}
		foreach ($values as $name => $value) {
421
			$this->setOldAttribute($name, $value);
422 423 424 425 426 427
		}
		$this->afterSave(true);
		return true;
	}

	/**
428
	 * Saves the changes to this active record into the associated Sphinx index.
429 430 431 432 433 434 435 436
	 *
	 * 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;
	 * 2. call [[afterValidate()]] when `$runValidation` is true.
	 * 3. call [[beforeSave()]]. If the method returns false, it will skip the
	 *    rest of the steps;
437
	 * 4. save the record into index. If this fails, it will skip the rest of the steps;
438 439 440 441 442 443 444 445
	 * 5. call [[afterSave()]];
	 *
	 * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
	 * [[EVENT_BEFORE_UPDATE]], [[EVENT_AFTER_UPDATE]] and [[EVENT_AFTER_VALIDATE]]
	 * will be raised by the corresponding methods.
	 *
	 * Only the [[changedAttributes|changed attribute values]] will be saved into database.
	 *
446
	 * For example, to update an article record:
447 448
	 *
	 * ~~~
449 450 451 452
	 * $article = Article::find(['id' => $id]);
	 * $article->genre_id = $genreId;
	 * $article->group_id = $groupId;
	 * $article->update();
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
	 * ~~~
	 *
	 * 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
	 * }
	 * ~~~
	 *
	 * @param boolean $runValidation whether to perform validation before saving the record.
	 * If the validation fails, the record will not be inserted into the 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 integer|boolean the number of rows affected, or false if validation fails
	 * or [[beforeSave()]] stops the updating process.
	 * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
	 * being updated is outdated.
	 * @throws \Exception in case update failed.
	 */
	public function update($runValidation = true, $attributes = null)
	{
		if ($runValidation && !$this->validate($attributes)) {
			return false;
		}
		$db = static::getDb();
		if ($this->isTransactional(self::OP_UPDATE) && $db->getTransaction() === null) {
			$transaction = $db->beginTransaction();
			try {
				$result = $this->updateInternal($attributes);
				if ($result === false) {
					$transaction->rollback();
				} else {
					$transaction->commit();
				}
			} catch (\Exception $e) {
				$transaction->rollback();
				throw $e;
			}
		} else {
			$result = $this->updateInternal($attributes);
		}
		return $result;
	}

	/**
	 * @see CActiveRecord::update()
	 * @throws StaleObjectException
	 */
506
	protected function updateInternal($attributes = null)
507 508 509 510 511 512 513 514 515
	{
		if (!$this->beforeSave(false)) {
			return false;
		}
		$values = $this->getDirtyAttributes($attributes);
		if (empty($values)) {
			$this->afterSave(false);
			return 0;
		}
516

517 518 519
		// Replace is supported only by runtime indexes and necessary only for field update
		$useReplace = false;
		$indexSchema = $this->getIndexSchema();
520
		if ($this->getIndexSchema()->isRuntime) {
521 522 523 524 525 526 527 528 529 530
			foreach ($values as $name => $value) {
				$columnSchema = $indexSchema->getColumn($name);
				if ($columnSchema->isField) {
					$useReplace = true;
					break;
				}
			}
		}

		if ($useReplace) {
531 532 533 534 535 536 537 538 539 540 541 542 543 544
			$values = array_merge($values, $this->getOldPrimaryKey(true));
			$command = static::getDb()->createCommand();
			$command->replace(static::indexName(), $values);
			// We do not check the return value of replace because it's possible
			// that the REPLACE statement doesn't change anything and thus returns 0.
			$rows = $command->execute();
		} else {
			$condition = $this->getOldPrimaryKey(true);
			$lock = $this->optimisticLock();
			if ($lock !== null) {
				if (!isset($values[$lock])) {
					$values[$lock] = $this->$lock + 1;
				}
				$condition[$lock] = $this->$lock;
545
			}
546 547 548
			// 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);
549

550 551 552
			if ($lock !== null && !$rows) {
				throw new StaleObjectException('The object being updated is outdated.');
			}
553 554 555
		}

		foreach ($values as $name => $value) {
556
			$this->setOldAttribute($name, $this->getAttribute($name));
557 558 559 560 561 562
		}
		$this->afterSave(false);
		return $rows;
	}

	/**
563
	 * Deletes the index entry corresponding to this active record.
564 565 566 567 568
	 *
	 * This method performs the following steps in order:
	 *
	 * 1. call [[beforeDelete()]]. If the method returns false, it will skip the
	 *    rest of the steps;
569
	 * 2. delete the record from the index;
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
	 * 3. call [[afterDelete()]].
	 *
	 * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
	 * will be raised by the corresponding methods.
	 *
	 * @return integer|boolean the number of rows deleted, or false if the deletion is unsuccessful for some reason.
	 * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
	 * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
	 * being deleted is outdated.
	 * @throws \Exception in case delete failed.
	 */
	public function delete()
	{
		$db = static::getDb();
		$transaction = $this->isTransactional(self::OP_DELETE) && $db->getTransaction() === null ? $db->beginTransaction() : null;
		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();
				if ($lock !== null) {
					$condition[$lock] = $this->$lock;
				}
				$result = $this->deleteAll($condition);
				if ($lock !== null && !$result) {
					throw new StaleObjectException('The object being deleted is outdated.');
				}
599
				$this->setOldAttributes(null);
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
				$this->afterDelete();
			}
			if ($transaction !== null) {
				if ($result === false) {
					$transaction->rollback();
				} else {
					$transaction->commit();
				}
			}
		} catch (\Exception $e) {
			if ($transaction !== null) {
				$transaction->rollback();
			}
			throw $e;
		}
		return $result;
	}

	/**
	 * Returns a value indicating whether the given active record is the same as the current one.
	 * The comparison is made by comparing the index names and the primary key values of the two active records.
621
	 * If one of the records [[isNewRecord|is new]] they are also considered not equal.
622 623 624 625 626
	 * @param ActiveRecord $record record to compare to
	 * @return boolean whether the two active records refer to the same row in the same index.
	 */
	public function equals($record)
	{
627 628 629
		if ($this->isNewRecord || $record->isNewRecord) {
			return false;
		}
630 631 632 633 634 635 636 637 638 639 640 641 642
		return $this->indexName() === $record->indexName() && $this->getPrimaryKey() === $record->getPrimaryKey();
	}

	/**
	 * Creates an active record object using a row of data.
	 * This method is called by [[ActiveQuery]] to populate the query results
	 * into Active Records. It is not meant to be used to create new records.
	 * @param array $row attribute values (name => value)
	 * @return ActiveRecord the newly created active record.
	 */
	public static function create($row)
	{
		$record = static::instantiate($row);
643
		$columns = static::getIndexSchema()->columns;
644 645 646 647 648 649
		foreach ($row as $name => $value) {
			if (isset($columns[$name])) {
				$column = $columns[$name];
				if ($column->isMva) {
					$value = explode(',', $value);
				}
650
				$record->setAttribute($name, $value);
651 652 653 654
			} else {
				$record->$name = $value;
			}
		}
655
		$record->setOldAttributes($record->getAttributes());
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
		$record->afterFind();
		return $record;
	}

	/**
	 * 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]].
	 */
	public function isTransactional($operation)
	{
		$scenario = $this->getScenario();
		$transactions = $this->transactions();
		return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
	}
671
}