ActiveRecord.php 29 KB

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