ActiveRecord.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db;
  8. use Yii;
  9. use yii\base\InvalidArgumentException;
  10. use yii\base\InvalidConfigException;
  11. use yii\helpers\ArrayHelper;
  12. use yii\helpers\Inflector;
  13. use yii\helpers\StringHelper;
  14. /**
  15. * ActiveRecord is the base class for classes representing relational data in terms of objects.
  16. *
  17. * Active Record implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record).
  18. * The premise behind Active Record is that an individual [[ActiveRecord]] object is associated with a specific
  19. * row in a database table. The object's attributes are mapped to the columns of the corresponding table.
  20. * Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.
  21. *
  22. * As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table.
  23. * This would mean that the class's `name` attribute is automatically mapped to the `name` column in `customer` table.
  24. * Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of
  25. * the `name` column for the table row, you can use the expression `$customer->name`.
  26. * In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
  27. * But Active Record provides much more functionality than this.
  28. *
  29. * To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and
  30. * implement the `tableName` method:
  31. *
  32. * ```php
  33. * <?php
  34. *
  35. * class Customer extends \yii\db\ActiveRecord
  36. * {
  37. * public static function tableName()
  38. * {
  39. * return 'customer';
  40. * }
  41. * }
  42. * ```
  43. *
  44. * The `tableName` method only has to return the name of the database table associated with the class.
  45. *
  46. * > Tip: You may also use the [Gii code generator](guide:start-gii) to generate ActiveRecord classes from your
  47. * > database tables.
  48. *
  49. * Class instances are obtained in one of two ways:
  50. *
  51. * * Using the `new` operator to create a new, empty object
  52. * * Using a method to fetch an existing record (or records) from the database
  53. *
  54. * Below is an example showing some typical usage of ActiveRecord:
  55. *
  56. * ```php
  57. * $user = new User();
  58. * $user->name = 'Qiang';
  59. * $user->save(); // a new row is inserted into user table
  60. *
  61. * // the following will retrieve the user 'CeBe' from the database
  62. * $user = User::find()->where(['name' => 'CeBe'])->one();
  63. *
  64. * // this will get related records from orders table when relation is defined
  65. * $orders = $user->orders;
  66. * ```
  67. *
  68. * For more details and usage information on ActiveRecord, see the [guide article on ActiveRecord](guide:db-active-record).
  69. *
  70. * @method ActiveQuery hasMany($class, array $link) see [[BaseActiveRecord::hasMany()]] for more info
  71. * @method ActiveQuery hasOne($class, array $link) see [[BaseActiveRecord::hasOne()]] for more info
  72. *
  73. * @author Qiang Xue <qiang.xue@gmail.com>
  74. * @author Carsten Brandt <mail@cebe.cc>
  75. * @since 2.0
  76. */
  77. class ActiveRecord extends BaseActiveRecord
  78. {
  79. /**
  80. * The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
  81. */
  82. const OP_INSERT = 0x01;
  83. /**
  84. * The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
  85. */
  86. const OP_UPDATE = 0x02;
  87. /**
  88. * The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
  89. */
  90. const OP_DELETE = 0x04;
  91. /**
  92. * All three operations: insert, update, delete.
  93. * This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE.
  94. */
  95. const OP_ALL = 0x07;
  96. /**
  97. * Loads default values from database table schema.
  98. *
  99. * You may call this method to load default values after creating a new instance:
  100. *
  101. * ```php
  102. * // class Customer extends \yii\db\ActiveRecord
  103. * $customer = new Customer();
  104. * $customer->loadDefaultValues();
  105. * ```
  106. *
  107. * @param bool $skipIfSet whether existing value should be preserved.
  108. * This will only set defaults for attributes that are `null`.
  109. * @return $this the model instance itself.
  110. */
  111. public function loadDefaultValues($skipIfSet = true)
  112. {
  113. foreach (static::getTableSchema()->columns as $column) {
  114. if ($column->defaultValue !== null && (!$skipIfSet || $this->{$column->name} === null)) {
  115. $this->{$column->name} = $column->defaultValue;
  116. }
  117. }
  118. return $this;
  119. }
  120. /**
  121. * Returns the database connection used by this AR class.
  122. * By default, the "db" application component is used as the database connection.
  123. * You may override this method if you want to use a different database connection.
  124. * @return Connection the database connection used by this AR class.
  125. */
  126. public static function getDb()
  127. {
  128. return Yii::$app->getDb();
  129. }
  130. /**
  131. * Creates an [[ActiveQuery]] instance with a given SQL statement.
  132. *
  133. * Note that because the SQL statement is already specified, calling additional
  134. * query modification methods (such as `where()`, `order()`) on the created [[ActiveQuery]]
  135. * instance will have no effect. However, calling `with()`, `asArray()` or `indexBy()` is
  136. * still fine.
  137. *
  138. * Below is an example:
  139. *
  140. * ```php
  141. * $customers = Customer::findBySql('SELECT * FROM customer')->all();
  142. * ```
  143. *
  144. * @param string $sql the SQL statement to be executed
  145. * @param array $params parameters to be bound to the SQL statement during execution.
  146. * @return ActiveQuery the newly created [[ActiveQuery]] instance
  147. */
  148. public static function findBySql($sql, $params = [])
  149. {
  150. $query = static::find();
  151. $query->sql = $sql;
  152. return $query->params($params);
  153. }
  154. /**
  155. * Finds ActiveRecord instance(s) by the given condition.
  156. * This method is internally called by [[findOne()]] and [[findAll()]].
  157. * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
  158. * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
  159. * @throws InvalidConfigException if there is no primary key defined.
  160. * @internal
  161. */
  162. protected static function findByCondition($condition)
  163. {
  164. $query = static::find();
  165. if (!ArrayHelper::isAssociative($condition)) {
  166. // query by primary key
  167. $primaryKey = static::primaryKey();
  168. if (isset($primaryKey[0])) {
  169. $pk = $primaryKey[0];
  170. if (!empty($query->join) || !empty($query->joinWith)) {
  171. $pk = static::tableName() . '.' . $pk;
  172. }
  173. // if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values
  174. $condition = [$pk => is_array($condition) ? array_values($condition) : $condition];
  175. } else {
  176. throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
  177. }
  178. } elseif (is_array($condition)) {
  179. $aliases = static::filterValidAliases($query);
  180. $condition = static::filterCondition($condition, $aliases);
  181. }
  182. return $query->andWhere($condition);
  183. }
  184. /**
  185. * Returns table aliases which are not the same as the name of the tables.
  186. *
  187. * @param Query $query
  188. * @return array
  189. * @throws InvalidConfigException
  190. * @since 2.0.17
  191. * @internal
  192. */
  193. protected static function filterValidAliases(Query $query)
  194. {
  195. $tables = $query->getTablesUsedInFrom();
  196. $aliases = array_diff(array_keys($tables), $tables);
  197. return array_map(function ($alias) {
  198. return preg_replace('/{{([\w]+)}}/', '$1', $alias);
  199. }, array_values($aliases));
  200. }
  201. /**
  202. * Filters array condition before it is assiged to a Query filter.
  203. *
  204. * This method will ensure that an array condition only filters on existing table columns.
  205. *
  206. * @param array $condition condition to filter.
  207. * @param array $aliases
  208. * @return array filtered condition.
  209. * @throws InvalidArgumentException in case array contains unsafe values.
  210. * @throws InvalidConfigException
  211. * @since 2.0.15
  212. * @internal
  213. */
  214. protected static function filterCondition(array $condition, array $aliases = [])
  215. {
  216. $result = [];
  217. $db = static::getDb();
  218. $columnNames = static::filterValidColumnNames($db, $aliases);
  219. foreach ($condition as $key => $value) {
  220. if (is_string($key) && !in_array($db->quoteSql($key), $columnNames, true)) {
  221. throw new InvalidArgumentException('Key "' . $key . '" is not a column name and can not be used as a filter');
  222. }
  223. $result[$key] = is_array($value) ? array_values($value) : $value;
  224. }
  225. return $result;
  226. }
  227. /**
  228. * Valid column names are table column names or column names prefixed with table name or table alias
  229. *
  230. * @param Connection $db
  231. * @param array $aliases
  232. * @return array
  233. * @throws InvalidConfigException
  234. * @since 2.0.17
  235. * @internal
  236. */
  237. protected static function filterValidColumnNames($db, array $aliases)
  238. {
  239. $columnNames = [];
  240. $tableName = static::tableName();
  241. $quotedTableName = $db->quoteTableName($tableName);
  242. foreach (static::getTableSchema()->getColumnNames() as $columnName) {
  243. $columnNames[] = $columnName;
  244. $columnNames[] = $db->quoteColumnName($columnName);
  245. $columnNames[] = "$tableName.$columnName";
  246. $columnNames[] = $db->quoteSql("$quotedTableName.[[$columnName]]");
  247. foreach ($aliases as $tableAlias) {
  248. $columnNames[] = "$tableAlias.$columnName";
  249. $quotedTableAlias = $db->quoteTableName($tableAlias);
  250. $columnNames[] = $db->quoteSql("$quotedTableAlias.[[$columnName]]");
  251. }
  252. }
  253. return $columnNames;
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function refresh()
  259. {
  260. $query = static::find();
  261. $tableName = key($query->getTablesUsedInFrom());
  262. $pk = [];
  263. // disambiguate column names in case ActiveQuery adds a JOIN
  264. foreach ($this->getPrimaryKey(true) as $key => $value) {
  265. $pk[$tableName . '.' . $key] = $value;
  266. }
  267. $query->where($pk);
  268. /* @var $record BaseActiveRecord */
  269. $record = $query->one();
  270. return $this->refreshInternal($record);
  271. }
  272. /**
  273. * Updates the whole table using the provided attribute values and conditions.
  274. *
  275. * For example, to change the status to be 1 for all customers whose status is 2:
  276. *
  277. * ```php
  278. * Customer::updateAll(['status' => 1], 'status = 2');
  279. * ```
  280. *
  281. * > Warning: If you do not specify any condition, this method will update **all** rows in the table.
  282. *
  283. * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or
  284. * [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then
  285. * call [[update()]] on each of them. For example an equivalent of the example above would be:
  286. *
  287. * ```php
  288. * $models = Customer::find()->where('status = 2')->all();
  289. * foreach ($models as $model) {
  290. * $model->status = 1;
  291. * $model->update(false); // skipping validation as no user input is involved
  292. * }
  293. * ```
  294. *
  295. * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
  296. *
  297. * @param array $attributes attribute values (name-value pairs) to be saved into the table
  298. * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
  299. * Please refer to [[Query::where()]] on how to specify this parameter.
  300. * @param array $params the parameters (name => value) to be bound to the query.
  301. * @return int the number of rows updated
  302. */
  303. public static function updateAll($attributes, $condition = '', $params = [])
  304. {
  305. $command = static::getDb()->createCommand();
  306. $command->update(static::tableName(), $attributes, $condition, $params);
  307. return $command->execute();
  308. }
  309. /**
  310. * Updates the whole table using the provided counter changes and conditions.
  311. *
  312. * For example, to increment all customers' age by 1,
  313. *
  314. * ```php
  315. * Customer::updateAllCounters(['age' => 1]);
  316. * ```
  317. *
  318. * Note that this method will not trigger any events.
  319. *
  320. * @param array $counters the counters to be updated (attribute name => increment value).
  321. * Use negative values if you want to decrement the counters.
  322. * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
  323. * Please refer to [[Query::where()]] on how to specify this parameter.
  324. * @param array $params the parameters (name => value) to be bound to the query.
  325. * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
  326. * @return int the number of rows updated
  327. */
  328. public static function updateAllCounters($counters, $condition = '', $params = [])
  329. {
  330. $n = 0;
  331. foreach ($counters as $name => $value) {
  332. $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
  333. $n++;
  334. }
  335. $command = static::getDb()->createCommand();
  336. $command->update(static::tableName(), $counters, $condition, $params);
  337. return $command->execute();
  338. }
  339. /**
  340. * Deletes rows in the table using the provided conditions.
  341. *
  342. * For example, to delete all customers whose status is 3:
  343. *
  344. * ```php
  345. * Customer::deleteAll('status = 3');
  346. * ```
  347. *
  348. * > Warning: If you do not specify any condition, this method will delete **all** rows in the table.
  349. *
  350. * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or
  351. * [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then
  352. * call [[delete()]] on each of them. For example an equivalent of the example above would be:
  353. *
  354. * ```php
  355. * $models = Customer::find()->where('status = 3')->all();
  356. * foreach ($models as $model) {
  357. * $model->delete();
  358. * }
  359. * ```
  360. *
  361. * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
  362. *
  363. * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
  364. * Please refer to [[Query::where()]] on how to specify this parameter.
  365. * @param array $params the parameters (name => value) to be bound to the query.
  366. * @return int the number of rows deleted
  367. */
  368. public static function deleteAll($condition = null, $params = [])
  369. {
  370. $command = static::getDb()->createCommand();
  371. $command->delete(static::tableName(), $condition, $params);
  372. return $command->execute();
  373. }
  374. /**
  375. * {@inheritdoc}
  376. * @return ActiveQuery the newly created [[ActiveQuery]] instance.
  377. */
  378. public static function find()
  379. {
  380. return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
  381. }
  382. /**
  383. * Declares the name of the database table associated with this AR class.
  384. * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
  385. * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
  386. * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
  387. * if the table is not named after this convention.
  388. * @return string the table name
  389. */
  390. public static function tableName()
  391. {
  392. return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
  393. }
  394. /**
  395. * Returns the schema information of the DB table associated with this AR class.
  396. * @return TableSchema the schema information of the DB table associated with this AR class.
  397. * @throws InvalidConfigException if the table for the AR class does not exist.
  398. */
  399. public static function getTableSchema()
  400. {
  401. $tableSchema = static::getDb()
  402. ->getSchema()
  403. ->getTableSchema(static::tableName());
  404. if ($tableSchema === null) {
  405. throw new InvalidConfigException('The table does not exist: ' . static::tableName());
  406. }
  407. return $tableSchema;
  408. }
  409. /**
  410. * Returns the primary key name(s) for this AR class.
  411. * The default implementation will return the primary key(s) as declared
  412. * in the DB table that is associated with this AR class.
  413. *
  414. * If the DB table does not declare any primary key, you should override
  415. * this method to return the attributes that you want to use as primary keys
  416. * for this AR class.
  417. *
  418. * Note that an array should be returned even for a table with single primary key.
  419. *
  420. * @return string[] the primary keys of the associated database table.
  421. */
  422. public static function primaryKey()
  423. {
  424. return static::getTableSchema()->primaryKey;
  425. }
  426. /**
  427. * Returns the list of all attribute names of the model.
  428. * The default implementation will return all column names of the table associated with this AR class.
  429. * @return array list of attribute names.
  430. */
  431. public function attributes()
  432. {
  433. return array_keys(static::getTableSchema()->columns);
  434. }
  435. /**
  436. * Declares which DB operations should be performed within a transaction in different scenarios.
  437. * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
  438. * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
  439. * By default, these methods are NOT enclosed in a DB transaction.
  440. *
  441. * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
  442. * in transactions. You can do so by overriding this method and returning the operations
  443. * that need to be transactional. For example,
  444. *
  445. * ```php
  446. * return [
  447. * 'admin' => self::OP_INSERT,
  448. * 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
  449. * // the above is equivalent to the following:
  450. * // 'api' => self::OP_ALL,
  451. *
  452. * ];
  453. * ```
  454. *
  455. * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
  456. * should be done in a transaction; and in the "api" scenario, all the operations should be done
  457. * in a transaction.
  458. *
  459. * @return array the declarations of transactional operations. The array keys are scenarios names,
  460. * and the array values are the corresponding transaction operations.
  461. */
  462. public function transactions()
  463. {
  464. return [];
  465. }
  466. /**
  467. * {@inheritdoc}
  468. */
  469. public static function populateRecord($record, $row)
  470. {
  471. $columns = static::getTableSchema()->columns;
  472. foreach ($row as $name => $value) {
  473. if (isset($columns[$name])) {
  474. $row[$name] = $columns[$name]->phpTypecast($value);
  475. }
  476. }
  477. parent::populateRecord($record, $row);
  478. }
  479. /**
  480. * Inserts a row into the associated database table using the attribute values of this record.
  481. *
  482. * This method performs the following steps in order:
  483. *
  484. * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
  485. * returns `false`, the rest of the steps will be skipped;
  486. * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
  487. * failed, the rest of the steps will be skipped;
  488. * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
  489. * the rest of the steps will be skipped;
  490. * 4. insert the record into database. If this fails, it will skip the rest of the steps;
  491. * 5. call [[afterSave()]];
  492. *
  493. * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
  494. * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
  495. * will be raised by the corresponding methods.
  496. *
  497. * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
  498. *
  499. * If the table's primary key is auto-incremental and is `null` during insertion,
  500. * it will be populated with the actual value after insertion.
  501. *
  502. * For example, to insert a customer record:
  503. *
  504. * ```php
  505. * $customer = new Customer;
  506. * $customer->name = $name;
  507. * $customer->email = $email;
  508. * $customer->insert();
  509. * ```
  510. *
  511. * @param bool $runValidation whether to perform validation (calling [[validate()]])
  512. * before saving the record. Defaults to `true`. If the validation fails, the record
  513. * will not be saved to the database and this method will return `false`.
  514. * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
  515. * meaning all attributes that are loaded from DB will be saved.
  516. * @return bool whether the attributes are valid and the record is inserted successfully.
  517. * @throws \Exception|\Throwable in case insert failed.
  518. */
  519. public function insert($runValidation = true, $attributes = null)
  520. {
  521. if ($runValidation && !$this->validate($attributes)) {
  522. Yii::info('Model not inserted due to validation error.', __METHOD__);
  523. return false;
  524. }
  525. if (!$this->isTransactional(self::OP_INSERT)) {
  526. return $this->insertInternal($attributes);
  527. }
  528. $transaction = static::getDb()->beginTransaction();
  529. try {
  530. $result = $this->insertInternal($attributes);
  531. if ($result === false) {
  532. $transaction->rollBack();
  533. } else {
  534. $transaction->commit();
  535. }
  536. return $result;
  537. } catch (\Exception $e) {
  538. $transaction->rollBack();
  539. throw $e;
  540. } catch (\Throwable $e) {
  541. $transaction->rollBack();
  542. throw $e;
  543. }
  544. }
  545. /**
  546. * Inserts an ActiveRecord into DB without considering transaction.
  547. * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
  548. * meaning all attributes that are loaded from DB will be saved.
  549. * @return bool whether the record is inserted successfully.
  550. */
  551. protected function insertInternal($attributes = null)
  552. {
  553. if (!$this->beforeSave(true)) {
  554. return false;
  555. }
  556. $values = $this->getDirtyAttributes($attributes);
  557. if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
  558. return false;
  559. }
  560. foreach ($primaryKeys as $name => $value) {
  561. $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
  562. $this->setAttribute($name, $id);
  563. $values[$name] = $id;
  564. }
  565. $changedAttributes = array_fill_keys(array_keys($values), null);
  566. $this->setOldAttributes($values);
  567. $this->afterSave(true, $changedAttributes);
  568. return true;
  569. }
  570. /**
  571. * Saves the changes to this active record into the associated database table.
  572. *
  573. * This method performs the following steps in order:
  574. *
  575. * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
  576. * returns `false`, the rest of the steps will be skipped;
  577. * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
  578. * failed, the rest of the steps will be skipped;
  579. * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
  580. * the rest of the steps will be skipped;
  581. * 4. save the record into database. If this fails, it will skip the rest of the steps;
  582. * 5. call [[afterSave()]];
  583. *
  584. * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
  585. * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
  586. * will be raised by the corresponding methods.
  587. *
  588. * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
  589. *
  590. * For example, to update a customer record:
  591. *
  592. * ```php
  593. * $customer = Customer::findOne($id);
  594. * $customer->name = $name;
  595. * $customer->email = $email;
  596. * $customer->update();
  597. * ```
  598. *
  599. * Note that it is possible the update does not affect any row in the table.
  600. * In this case, this method will return 0. For this reason, you should use the following
  601. * code to check if update() is successful or not:
  602. *
  603. * ```php
  604. * if ($customer->update() !== false) {
  605. * // update successful
  606. * } else {
  607. * // update failed
  608. * }
  609. * ```
  610. *
  611. * @param bool $runValidation whether to perform validation (calling [[validate()]])
  612. * before saving the record. Defaults to `true`. If the validation fails, the record
  613. * will not be saved to the database and this method will return `false`.
  614. * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
  615. * meaning all attributes that are loaded from DB will be saved.
  616. * @return int|false the number of rows affected, or false if validation fails
  617. * or [[beforeSave()]] stops the updating process.
  618. * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
  619. * being updated is outdated.
  620. * @throws \Exception|\Throwable in case update failed.
  621. */
  622. public function update($runValidation = true, $attributeNames = null)
  623. {
  624. if ($runValidation && !$this->validate($attributeNames)) {
  625. Yii::info('Model not updated due to validation error.', __METHOD__);
  626. return false;
  627. }
  628. if (!$this->isTransactional(self::OP_UPDATE)) {
  629. return $this->updateInternal($attributeNames);
  630. }
  631. $transaction = static::getDb()->beginTransaction();
  632. try {
  633. $result = $this->updateInternal($attributeNames);
  634. if ($result === false) {
  635. $transaction->rollBack();
  636. } else {
  637. $transaction->commit();
  638. }
  639. return $result;
  640. } catch (\Exception $e) {
  641. $transaction->rollBack();
  642. throw $e;
  643. } catch (\Throwable $e) {
  644. $transaction->rollBack();
  645. throw $e;
  646. }
  647. }
  648. /**
  649. * Deletes the table row corresponding to this active record.
  650. *
  651. * This method performs the following steps in order:
  652. *
  653. * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
  654. * rest of the steps;
  655. * 2. delete the record from the database;
  656. * 3. call [[afterDelete()]].
  657. *
  658. * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
  659. * will be raised by the corresponding methods.
  660. *
  661. * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  662. * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
  663. * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
  664. * being deleted is outdated.
  665. * @throws \Exception|\Throwable in case delete failed.
  666. */
  667. public function delete()
  668. {
  669. if (!$this->isTransactional(self::OP_DELETE)) {
  670. return $this->deleteInternal();
  671. }
  672. $transaction = static::getDb()->beginTransaction();
  673. try {
  674. $result = $this->deleteInternal();
  675. if ($result === false) {
  676. $transaction->rollBack();
  677. } else {
  678. $transaction->commit();
  679. }
  680. return $result;
  681. } catch (\Exception $e) {
  682. $transaction->rollBack();
  683. throw $e;
  684. } catch (\Throwable $e) {
  685. $transaction->rollBack();
  686. throw $e;
  687. }
  688. }
  689. /**
  690. * Deletes an ActiveRecord without considering transaction.
  691. * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  692. * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
  693. * @throws StaleObjectException
  694. */
  695. protected function deleteInternal()
  696. {
  697. if (!$this->beforeDelete()) {
  698. return false;
  699. }
  700. // we do not check the return value of deleteAll() because it's possible
  701. // the record is already deleted in the database and thus the method will return 0
  702. $condition = $this->getOldPrimaryKey(true);
  703. $lock = $this->optimisticLock();
  704. if ($lock !== null) {
  705. $condition[$lock] = $this->$lock;
  706. }
  707. $result = static::deleteAll($condition);
  708. if ($lock !== null && !$result) {
  709. throw new StaleObjectException('The object being deleted is outdated.');
  710. }
  711. $this->setOldAttributes(null);
  712. $this->afterDelete();
  713. return $result;
  714. }
  715. /**
  716. * Returns a value indicating whether the given active record is the same as the current one.
  717. * The comparison is made by comparing the table names and the primary key values of the two active records.
  718. * If one of the records [[isNewRecord|is new]] they are also considered not equal.
  719. * @param ActiveRecord $record record to compare to
  720. * @return bool whether the two active records refer to the same row in the same database table.
  721. */
  722. public function equals($record)
  723. {
  724. if ($this->isNewRecord || $record->isNewRecord) {
  725. return false;
  726. }
  727. return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
  728. }
  729. /**
  730. * Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].
  731. * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
  732. * @return bool whether the specified operation is transactional in the current [[scenario]].
  733. */
  734. public function isTransactional($operation)
  735. {
  736. $scenario = $this->getScenario();
  737. $transactions = $this->transactions();
  738. return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
  739. }
  740. }