ActiveRecord.php 31 KB

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