You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

655 lines
25KB

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