ActiveRecord.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. $condition = static::filterCondition($condition);
  180. }
  181. return $query->andWhere($condition);
  182. }
  183. /**
  184. * Filters array condition before it is assiged to a Query filter.
  185. *
  186. * This method will ensure that an array condition only filters on existing table columns.
  187. *
  188. * @param array $condition condition to filter.
  189. * @return array filtered condition.
  190. * @throws InvalidArgumentException in case array contains unsafe values.
  191. * @since 2.0.15
  192. * @internal
  193. */
  194. protected static function filterCondition(array $condition)
  195. {
  196. $result = [];
  197. // valid column names are table column names or column names prefixed with table name
  198. $columnNames = static::getTableSchema()->getColumnNames();
  199. $tableName = static::tableName();
  200. $columnNames = array_merge($columnNames, array_map(function($columnName) use ($tableName) {
  201. return "$tableName.$columnName";
  202. }, $columnNames));
  203. foreach ($condition as $key => $value) {
  204. if (is_string($key) && !in_array($key, $columnNames, true)) {
  205. throw new InvalidArgumentException('Key "' . $key . '" is not a column name and can not be used as a filter');
  206. }
  207. $result[$key] = is_array($value) ? array_values($value) : $value;
  208. }
  209. return $result;
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. public function refresh()
  215. {
  216. $query = static::find();
  217. $tableName = key($query->getTablesUsedInFrom());
  218. $pk = [];
  219. // disambiguate column names in case ActiveQuery adds a JOIN
  220. foreach ($this->getPrimaryKey(true) as $key => $value) {
  221. $pk[$tableName . '.' . $key] = $value;
  222. }
  223. $query->where($pk);
  224. /* @var $record BaseActiveRecord */
  225. $record = $query->one();
  226. return $this->refreshInternal($record);
  227. }
  228. /**
  229. * Updates the whole table using the provided attribute values and conditions.
  230. *
  231. * For example, to change the status to be 1 for all customers whose status is 2:
  232. *
  233. * ```php
  234. * Customer::updateAll(['status' => 1], 'status = 2');
  235. * ```
  236. *
  237. * > Warning: If you do not specify any condition, this method will update **all** rows in the table.
  238. *
  239. * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or
  240. * [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then
  241. * call [[update()]] on each of them. For example an equivalent of the example above would be:
  242. *
  243. * ```php
  244. * $models = Customer::find()->where('status = 2')->all();
  245. * foreach ($models as $model) {
  246. * $model->status = 1;
  247. * $model->update(false); // skipping validation as no user input is involved
  248. * }
  249. * ```
  250. *
  251. * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
  252. *
  253. * @param array $attributes attribute values (name-value pairs) to be saved into the table
  254. * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
  255. * Please refer to [[Query::where()]] on how to specify this parameter.
  256. * @param array $params the parameters (name => value) to be bound to the query.
  257. * @return int the number of rows updated
  258. */
  259. public static function updateAll($attributes, $condition = '', $params = [])
  260. {
  261. $command = static::getDb()->createCommand();
  262. $command->update(static::tableName(), $attributes, $condition, $params);
  263. return $command->execute();
  264. }
  265. /**
  266. * Updates the whole table using the provided counter changes and conditions.
  267. *
  268. * For example, to increment all customers' age by 1,
  269. *
  270. * ```php
  271. * Customer::updateAllCounters(['age' => 1]);
  272. * ```
  273. *
  274. * Note that this method will not trigger any events.
  275. *
  276. * @param array $counters the counters to be updated (attribute name => increment value).
  277. * Use negative values if you want to decrement the counters.
  278. * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
  279. * Please refer to [[Query::where()]] on how to specify this parameter.
  280. * @param array $params the parameters (name => value) to be bound to the query.
  281. * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
  282. * @return int the number of rows updated
  283. */
  284. public static function updateAllCounters($counters, $condition = '', $params = [])
  285. {
  286. $n = 0;
  287. foreach ($counters as $name => $value) {
  288. $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
  289. $n++;
  290. }
  291. $command = static::getDb()->createCommand();
  292. $command->update(static::tableName(), $counters, $condition, $params);
  293. return $command->execute();
  294. }
  295. /**
  296. * Deletes rows in the table using the provided conditions.
  297. *
  298. * For example, to delete all customers whose status is 3:
  299. *
  300. * ```php
  301. * Customer::deleteAll('status = 3');
  302. * ```
  303. *
  304. * > Warning: If you do not specify any condition, this method will delete **all** rows in the table.
  305. *
  306. * Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or
  307. * [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then
  308. * call [[delete()]] on each of them. For example an equivalent of the example above would be:
  309. *
  310. * ```php
  311. * $models = Customer::find()->where('status = 3')->all();
  312. * foreach ($models as $model) {
  313. * $model->delete();
  314. * }
  315. * ```
  316. *
  317. * For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.
  318. *
  319. * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL.
  320. * Please refer to [[Query::where()]] on how to specify this parameter.
  321. * @param array $params the parameters (name => value) to be bound to the query.
  322. * @return int the number of rows deleted
  323. */
  324. public static function deleteAll($condition = null, $params = [])
  325. {
  326. $command = static::getDb()->createCommand();
  327. $command->delete(static::tableName(), $condition, $params);
  328. return $command->execute();
  329. }
  330. /**
  331. * {@inheritdoc}
  332. * @return ActiveQuery the newly created [[ActiveQuery]] instance.
  333. */
  334. public static function find()
  335. {
  336. return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
  337. }
  338. /**
  339. * Declares the name of the database table associated with this AR class.
  340. * By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
  341. * with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is `tbl_`,
  342. * `Customer` becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method
  343. * if the table is not named after this convention.
  344. * @return string the table name
  345. */
  346. public static function tableName()
  347. {
  348. return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
  349. }
  350. /**
  351. * Returns the schema information of the DB table associated with this AR class.
  352. * @return TableSchema the schema information of the DB table associated with this AR class.
  353. * @throws InvalidConfigException if the table for the AR class does not exist.
  354. */
  355. public static function getTableSchema()
  356. {
  357. $tableSchema = static::getDb()
  358. ->getSchema()
  359. ->getTableSchema(static::tableName());
  360. if ($tableSchema === null) {
  361. throw new InvalidConfigException('The table does not exist: ' . static::tableName());
  362. }
  363. return $tableSchema;
  364. }
  365. /**
  366. * Returns the primary key name(s) for this AR class.
  367. * The default implementation will return the primary key(s) as declared
  368. * in the DB table that is associated with this AR class.
  369. *
  370. * If the DB table does not declare any primary key, you should override
  371. * this method to return the attributes that you want to use as primary keys
  372. * for this AR class.
  373. *
  374. * Note that an array should be returned even for a table with single primary key.
  375. *
  376. * @return string[] the primary keys of the associated database table.
  377. */
  378. public static function primaryKey()
  379. {
  380. return static::getTableSchema()->primaryKey;
  381. }
  382. /**
  383. * Returns the list of all attribute names of the model.
  384. * The default implementation will return all column names of the table associated with this AR class.
  385. * @return array list of attribute names.
  386. */
  387. public function attributes()
  388. {
  389. return array_keys(static::getTableSchema()->columns);
  390. }
  391. /**
  392. * Declares which DB operations should be performed within a transaction in different scenarios.
  393. * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
  394. * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
  395. * By default, these methods are NOT enclosed in a DB transaction.
  396. *
  397. * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
  398. * in transactions. You can do so by overriding this method and returning the operations
  399. * that need to be transactional. For example,
  400. *
  401. * ```php
  402. * return [
  403. * 'admin' => self::OP_INSERT,
  404. * 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
  405. * // the above is equivalent to the following:
  406. * // 'api' => self::OP_ALL,
  407. *
  408. * ];
  409. * ```
  410. *
  411. * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
  412. * should be done in a transaction; and in the "api" scenario, all the operations should be done
  413. * in a transaction.
  414. *
  415. * @return array the declarations of transactional operations. The array keys are scenarios names,
  416. * and the array values are the corresponding transaction operations.
  417. */
  418. public function transactions()
  419. {
  420. return [];
  421. }
  422. /**
  423. * {@inheritdoc}
  424. */
  425. public static function populateRecord($record, $row)
  426. {
  427. $columns = static::getTableSchema()->columns;
  428. foreach ($row as $name => $value) {
  429. if (isset($columns[$name])) {
  430. $row[$name] = $columns[$name]->phpTypecast($value);
  431. }
  432. }
  433. parent::populateRecord($record, $row);
  434. }
  435. /**
  436. * Inserts a row into the associated database table using the attribute values of this record.
  437. *
  438. * This method performs the following steps in order:
  439. *
  440. * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
  441. * returns `false`, the rest of the steps will be skipped;
  442. * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
  443. * failed, the rest of the steps will be skipped;
  444. * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
  445. * the rest of the steps will be skipped;
  446. * 4. insert the record into database. If this fails, it will skip the rest of the steps;
  447. * 5. call [[afterSave()]];
  448. *
  449. * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
  450. * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
  451. * will be raised by the corresponding methods.
  452. *
  453. * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
  454. *
  455. * If the table's primary key is auto-incremental and is `null` during insertion,
  456. * it will be populated with the actual value after insertion.
  457. *
  458. * For example, to insert a customer record:
  459. *
  460. * ```php
  461. * $customer = new Customer;
  462. * $customer->name = $name;
  463. * $customer->email = $email;
  464. * $customer->insert();
  465. * ```
  466. *
  467. * @param bool $runValidation whether to perform validation (calling [[validate()]])
  468. * before saving the record. Defaults to `true`. If the validation fails, the record
  469. * will not be saved to the database and this method will return `false`.
  470. * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
  471. * meaning all attributes that are loaded from DB will be saved.
  472. * @return bool whether the attributes are valid and the record is inserted successfully.
  473. * @throws \Exception|\Throwable in case insert failed.
  474. */
  475. public function insert($runValidation = true, $attributes = null)
  476. {
  477. if ($runValidation && !$this->validate($attributes)) {
  478. Yii::info('Model not inserted due to validation error.', __METHOD__);
  479. return false;
  480. }
  481. if (!$this->isTransactional(self::OP_INSERT)) {
  482. return $this->insertInternal($attributes);
  483. }
  484. $transaction = static::getDb()->beginTransaction();
  485. try {
  486. $result = $this->insertInternal($attributes);
  487. if ($result === false) {
  488. $transaction->rollBack();
  489. } else {
  490. $transaction->commit();
  491. }
  492. return $result;
  493. } catch (\Exception $e) {
  494. $transaction->rollBack();
  495. throw $e;
  496. } catch (\Throwable $e) {
  497. $transaction->rollBack();
  498. throw $e;
  499. }
  500. }
  501. /**
  502. * Inserts an ActiveRecord into DB without considering transaction.
  503. * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
  504. * meaning all attributes that are loaded from DB will be saved.
  505. * @return bool whether the record is inserted successfully.
  506. */
  507. protected function insertInternal($attributes = null)
  508. {
  509. if (!$this->beforeSave(true)) {
  510. return false;
  511. }
  512. $values = $this->getDirtyAttributes($attributes);
  513. if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
  514. return false;
  515. }
  516. foreach ($primaryKeys as $name => $value) {
  517. $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
  518. $this->setAttribute($name, $id);
  519. $values[$name] = $id;
  520. }
  521. $changedAttributes = array_fill_keys(array_keys($values), null);
  522. $this->setOldAttributes($values);
  523. $this->afterSave(true, $changedAttributes);
  524. return true;
  525. }
  526. /**
  527. * Saves the changes to this active record into the associated database table.
  528. *
  529. * This method performs the following steps in order:
  530. *
  531. * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
  532. * returns `false`, the rest of the steps will be skipped;
  533. * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
  534. * failed, the rest of the steps will be skipped;
  535. * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
  536. * the rest of the steps will be skipped;
  537. * 4. save the record into database. If this fails, it will skip the rest of the steps;
  538. * 5. call [[afterSave()]];
  539. *
  540. * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
  541. * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
  542. * will be raised by the corresponding methods.
  543. *
  544. * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
  545. *
  546. * For example, to update a customer record:
  547. *
  548. * ```php
  549. * $customer = Customer::findOne($id);
  550. * $customer->name = $name;
  551. * $customer->email = $email;
  552. * $customer->update();
  553. * ```
  554. *
  555. * Note that it is possible the update does not affect any row in the table.
  556. * In this case, this method will return 0. For this reason, you should use the following
  557. * code to check if update() is successful or not:
  558. *
  559. * ```php
  560. * if ($customer->update() !== false) {
  561. * // update successful
  562. * } else {
  563. * // update failed
  564. * }
  565. * ```
  566. *
  567. * @param bool $runValidation whether to perform validation (calling [[validate()]])
  568. * before saving the record. Defaults to `true`. If the validation fails, the record
  569. * will not be saved to the database and this method will return `false`.
  570. * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
  571. * meaning all attributes that are loaded from DB will be saved.
  572. * @return int|false the number of rows affected, or false if validation fails
  573. * or [[beforeSave()]] stops the updating process.
  574. * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
  575. * being updated is outdated.
  576. * @throws \Exception|\Throwable in case update failed.
  577. */
  578. public function update($runValidation = true, $attributeNames = null)
  579. {
  580. if ($runValidation && !$this->validate($attributeNames)) {
  581. Yii::info('Model not updated due to validation error.', __METHOD__);
  582. return false;
  583. }
  584. if (!$this->isTransactional(self::OP_UPDATE)) {
  585. return $this->updateInternal($attributeNames);
  586. }
  587. $transaction = static::getDb()->beginTransaction();
  588. try {
  589. $result = $this->updateInternal($attributeNames);
  590. if ($result === false) {
  591. $transaction->rollBack();
  592. } else {
  593. $transaction->commit();
  594. }
  595. return $result;
  596. } catch (\Exception $e) {
  597. $transaction->rollBack();
  598. throw $e;
  599. } catch (\Throwable $e) {
  600. $transaction->rollBack();
  601. throw $e;
  602. }
  603. }
  604. /**
  605. * Deletes the table row corresponding to this active record.
  606. *
  607. * This method performs the following steps in order:
  608. *
  609. * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
  610. * rest of the steps;
  611. * 2. delete the record from the database;
  612. * 3. call [[afterDelete()]].
  613. *
  614. * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
  615. * will be raised by the corresponding methods.
  616. *
  617. * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  618. * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
  619. * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
  620. * being deleted is outdated.
  621. * @throws \Exception|\Throwable in case delete failed.
  622. */
  623. public function delete()
  624. {
  625. if (!$this->isTransactional(self::OP_DELETE)) {
  626. return $this->deleteInternal();
  627. }
  628. $transaction = static::getDb()->beginTransaction();
  629. try {
  630. $result = $this->deleteInternal();
  631. if ($result === false) {
  632. $transaction->rollBack();
  633. } else {
  634. $transaction->commit();
  635. }
  636. return $result;
  637. } catch (\Exception $e) {
  638. $transaction->rollBack();
  639. throw $e;
  640. } catch (\Throwable $e) {
  641. $transaction->rollBack();
  642. throw $e;
  643. }
  644. }
  645. /**
  646. * Deletes an ActiveRecord without considering transaction.
  647. * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  648. * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
  649. * @throws StaleObjectException
  650. */
  651. protected function deleteInternal()
  652. {
  653. if (!$this->beforeDelete()) {
  654. return false;
  655. }
  656. // we do not check the return value of deleteAll() because it's possible
  657. // the record is already deleted in the database and thus the method will return 0
  658. $condition = $this->getOldPrimaryKey(true);
  659. $lock = $this->optimisticLock();
  660. if ($lock !== null) {
  661. $condition[$lock] = $this->$lock;
  662. }
  663. $result = static::deleteAll($condition);
  664. if ($lock !== null && !$result) {
  665. throw new StaleObjectException('The object being deleted is outdated.');
  666. }
  667. $this->setOldAttributes(null);
  668. $this->afterDelete();
  669. return $result;
  670. }
  671. /**
  672. * Returns a value indicating whether the given active record is the same as the current one.
  673. * The comparison is made by comparing the table names and the primary key values of the two active records.
  674. * If one of the records [[isNewRecord|is new]] they are also considered not equal.
  675. * @param ActiveRecord $record record to compare to
  676. * @return bool whether the two active records refer to the same row in the same database table.
  677. */
  678. public function equals($record)
  679. {
  680. if ($this->isNewRecord || $record->isNewRecord) {
  681. return false;
  682. }
  683. return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
  684. }
  685. /**
  686. * Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].
  687. * @param int $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
  688. * @return bool whether the specified operation is transactional in the current [[scenario]].
  689. */
  690. public function isTransactional($operation)
  691. {
  692. $scenario = $this->getScenario();
  693. $transactions = $this->transactions();
  694. return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
  695. }
  696. }