選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

649 行
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. * 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 boolean $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. * For example, to change the status to be 1 for all customers whose status is 2:
  182. *
  183. * ```php
  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. * ```php
  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. * ```php
  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. $tableSchema = static::getDb()
  275. ->getSchema()
  276. ->getTableSchema(static::tableName());
  277. if ($tableSchema === null) {
  278. throw new InvalidConfigException('The table does not exist: ' . static::tableName());
  279. }
  280. return $tableSchema;
  281. }
  282. /**
  283. * Returns the primary key name(s) for this AR class.
  284. * The default implementation will return the primary key(s) as declared
  285. * in the DB table that is associated with this AR class.
  286. *
  287. * If the DB table does not declare any primary key, you should override
  288. * this method to return the attributes that you want to use as primary keys
  289. * for this AR class.
  290. *
  291. * Note that an array should be returned even for a table with single primary key.
  292. *
  293. * @return string[] the primary keys of the associated database table.
  294. */
  295. public static function primaryKey()
  296. {
  297. return static::getTableSchema()->primaryKey;
  298. }
  299. /**
  300. * Returns the list of all attribute names of the model.
  301. * The default implementation will return all column names of the table associated with this AR class.
  302. * @return array list of attribute names.
  303. */
  304. public function attributes()
  305. {
  306. return array_keys(static::getTableSchema()->columns);
  307. }
  308. /**
  309. * Declares which DB operations should be performed within a transaction in different scenarios.
  310. * The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
  311. * which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively.
  312. * By default, these methods are NOT enclosed in a DB transaction.
  313. *
  314. * In some scenarios, to ensure data consistency, you may want to enclose some or all of them
  315. * in transactions. You can do so by overriding this method and returning the operations
  316. * that need to be transactional. For example,
  317. *
  318. * ```php
  319. * return [
  320. * 'admin' => self::OP_INSERT,
  321. * 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
  322. * // the above is equivalent to the following:
  323. * // 'api' => self::OP_ALL,
  324. *
  325. * ];
  326. * ```
  327. *
  328. * The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]])
  329. * should be done in a transaction; and in the "api" scenario, all the operations should be done
  330. * in a transaction.
  331. *
  332. * @return array the declarations of transactional operations. The array keys are scenarios names,
  333. * and the array values are the corresponding transaction operations.
  334. */
  335. public function transactions()
  336. {
  337. return [];
  338. }
  339. /**
  340. * @inheritdoc
  341. */
  342. public static function populateRecord($record, $row)
  343. {
  344. $columns = static::getTableSchema()->columns;
  345. foreach ($row as $name => $value) {
  346. if (isset($columns[$name])) {
  347. $row[$name] = $columns[$name]->phpTypecast($value);
  348. }
  349. }
  350. parent::populateRecord($record, $row);
  351. }
  352. /**
  353. * Inserts a row into the associated database table using the attribute values of this record.
  354. *
  355. * This method performs the following steps in order:
  356. *
  357. * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
  358. * returns `false`, the rest of the steps will be skipped;
  359. * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
  360. * failed, the rest of the steps will be skipped;
  361. * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
  362. * the rest of the steps will be skipped;
  363. * 4. insert the record into database. If this fails, it will skip the rest of the steps;
  364. * 5. call [[afterSave()]];
  365. *
  366. * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
  367. * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_INSERT]], and [[EVENT_AFTER_INSERT]]
  368. * will be raised by the corresponding methods.
  369. *
  370. * Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
  371. *
  372. * If the table's primary key is auto-incremental and is `null` during insertion,
  373. * it will be populated with the actual value after insertion.
  374. *
  375. * For example, to insert a customer record:
  376. *
  377. * ```php
  378. * $customer = new Customer;
  379. * $customer->name = $name;
  380. * $customer->email = $email;
  381. * $customer->insert();
  382. * ```
  383. *
  384. * @param boolean $runValidation whether to perform validation (calling [[validate()]])
  385. * before saving the record. Defaults to `true`. If the validation fails, the record
  386. * will not be saved to the database and this method will return `false`.
  387. * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
  388. * meaning all attributes that are loaded from DB will be saved.
  389. * @return boolean whether the attributes are valid and the record is inserted successfully.
  390. * @throws \Exception in case insert failed.
  391. */
  392. public function insert($runValidation = true, $attributes = null)
  393. {
  394. if ($runValidation && !$this->validate($attributes)) {
  395. Yii::info('Model not inserted due to validation error.', __METHOD__);
  396. return false;
  397. }
  398. if (!$this->isTransactional(self::OP_INSERT)) {
  399. return $this->insertInternal($attributes);
  400. }
  401. $transaction = static::getDb()->beginTransaction();
  402. try {
  403. $result = $this->insertInternal($attributes);
  404. if ($result === false) {
  405. $transaction->rollBack();
  406. } else {
  407. $transaction->commit();
  408. }
  409. return $result;
  410. } catch (\Exception $e) {
  411. $transaction->rollBack();
  412. throw $e;
  413. }
  414. }
  415. /**
  416. * Inserts an ActiveRecord into DB without considering transaction.
  417. * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
  418. * meaning all attributes that are loaded from DB will be saved.
  419. * @return boolean whether the record is inserted successfully.
  420. */
  421. protected function insertInternal($attributes = null)
  422. {
  423. if (!$this->beforeSave(true)) {
  424. return false;
  425. }
  426. $values = $this->getDirtyAttributes($attributes);
  427. if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
  428. return false;
  429. }
  430. foreach ($primaryKeys as $name => $value) {
  431. $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
  432. $this->setAttribute($name, $id);
  433. $values[$name] = $id;
  434. }
  435. $changedAttributes = array_fill_keys(array_keys($values), null);
  436. $this->setOldAttributes($values);
  437. $this->afterSave(true, $changedAttributes);
  438. return true;
  439. }
  440. /**
  441. * Saves the changes to this active record into the associated database table.
  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. save 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_UPDATE]], and [[EVENT_AFTER_UPDATE]]
  456. * will be raised by the corresponding methods.
  457. *
  458. * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
  459. *
  460. * For example, to update a customer record:
  461. *
  462. * ```php
  463. * $customer = Customer::findOne($id);
  464. * $customer->name = $name;
  465. * $customer->email = $email;
  466. * $customer->update();
  467. * ```
  468. *
  469. * Note that it is possible the update does not affect any row in the table.
  470. * In this case, this method will return 0. For this reason, you should use the following
  471. * code to check if update() is successful or not:
  472. *
  473. * ```php
  474. * if ($customer->update() !== false) {
  475. * // update successful
  476. * } else {
  477. * // update failed
  478. * }
  479. * ```
  480. *
  481. * @param boolean $runValidation whether to perform validation (calling [[validate()]])
  482. * before saving the record. Defaults to `true`. If the validation fails, the record
  483. * will not be saved to the database and this method will return `false`.
  484. * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
  485. * meaning all attributes that are loaded from DB will be saved.
  486. * @return integer|false the number of rows affected, or false if validation fails
  487. * or [[beforeSave()]] stops the updating process.
  488. * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
  489. * being updated is outdated.
  490. * @throws \Exception in case update failed.
  491. */
  492. public function update($runValidation = true, $attributeNames = null)
  493. {
  494. if ($runValidation && !$this->validate($attributeNames)) {
  495. Yii::info('Model not updated due to validation error.', __METHOD__);
  496. return false;
  497. }
  498. if (!$this->isTransactional(self::OP_UPDATE)) {
  499. return $this->updateInternal($attributeNames);
  500. }
  501. $transaction = static::getDb()->beginTransaction();
  502. try {
  503. $result = $this->updateInternal($attributeNames);
  504. if ($result === false) {
  505. $transaction->rollBack();
  506. } else {
  507. $transaction->commit();
  508. }
  509. return $result;
  510. } catch (\Exception $e) {
  511. $transaction->rollBack();
  512. throw $e;
  513. }
  514. }
  515. /**
  516. * Deletes the table row corresponding to this active record.
  517. *
  518. * This method performs the following steps in order:
  519. *
  520. * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
  521. * rest of the steps;
  522. * 2. delete the record from the database;
  523. * 3. call [[afterDelete()]].
  524. *
  525. * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
  526. * will be raised by the corresponding methods.
  527. *
  528. * @return integer|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  529. * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
  530. * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
  531. * being deleted is outdated.
  532. * @throws \Exception in case delete failed.
  533. */
  534. public function delete()
  535. {
  536. if (!$this->isTransactional(self::OP_DELETE)) {
  537. return $this->deleteInternal();
  538. }
  539. $transaction = static::getDb()->beginTransaction();
  540. try {
  541. $result = $this->deleteInternal();
  542. if ($result === false) {
  543. $transaction->rollBack();
  544. } else {
  545. $transaction->commit();
  546. }
  547. return $result;
  548. } catch (\Exception $e) {
  549. $transaction->rollBack();
  550. throw $e;
  551. }
  552. }
  553. /**
  554. * Deletes an ActiveRecord without considering transaction.
  555. * @return integer|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  556. * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
  557. * @throws StaleObjectException
  558. */
  559. protected function deleteInternal()
  560. {
  561. if (!$this->beforeDelete()) {
  562. return false;
  563. }
  564. // we do not check the return value of deleteAll() because it's possible
  565. // the record is already deleted in the database and thus the method will return 0
  566. $condition = $this->getOldPrimaryKey(true);
  567. $lock = $this->optimisticLock();
  568. if ($lock !== null) {
  569. $condition[$lock] = $this->$lock;
  570. }
  571. $result = static::deleteAll($condition);
  572. if ($lock !== null && !$result) {
  573. throw new StaleObjectException('The object being deleted is outdated.');
  574. }
  575. $this->setOldAttributes(null);
  576. $this->afterDelete();
  577. return $result;
  578. }
  579. /**
  580. * Returns a value indicating whether the given active record is the same as the current one.
  581. * The comparison is made by comparing the table names and the primary key values of the two active records.
  582. * If one of the records [[isNewRecord|is new]] they are also considered not equal.
  583. * @param ActiveRecord $record record to compare to
  584. * @return boolean whether the two active records refer to the same row in the same database table.
  585. */
  586. public function equals($record)
  587. {
  588. if ($this->isNewRecord || $record->isNewRecord) {
  589. return false;
  590. }
  591. return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
  592. }
  593. /**
  594. * Returns a value indicating whether the specified operation is transactional in the current [[scenario]].
  595. * @param integer $operation the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].
  596. * @return boolean whether the specified operation is transactional in the current [[scenario]].
  597. */
  598. public function isTransactional($operation)
  599. {
  600. $scenario = $this->getScenario();
  601. $transactions = $this->transactions();
  602. return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
  603. }
  604. }