ActiveRecord.php 27 KB

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