ActiveRecordInterface.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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\base\StaticInstanceInterface;
  9. /**
  10. * ActiveRecordInterface.
  11. *
  12. * @author Qiang Xue <qiang.xue@gmail.com>
  13. * @author Carsten Brandt <mail@cebe.cc>
  14. * @since 2.0
  15. */
  16. interface ActiveRecordInterface extends StaticInstanceInterface
  17. {
  18. /**
  19. * Returns the primary key **name(s)** for this AR class.
  20. *
  21. * Note that an array should be returned even when the record only has a single primary key.
  22. *
  23. * For the primary key **value** see [[getPrimaryKey()]] instead.
  24. *
  25. * @return string[] the primary key name(s) for this AR class.
  26. */
  27. public static function primaryKey();
  28. /**
  29. * Returns the list of all attribute names of the record.
  30. * @return array list of attribute names.
  31. */
  32. public function attributes();
  33. /**
  34. * Returns the named attribute value.
  35. * If this record is the result of a query and the attribute is not loaded,
  36. * `null` will be returned.
  37. * @param string $name the attribute name
  38. * @return mixed the attribute value. `null` if the attribute is not set or does not exist.
  39. * @see hasAttribute()
  40. */
  41. public function getAttribute($name);
  42. /**
  43. * Sets the named attribute value.
  44. * @param string $name the attribute name.
  45. * @param mixed $value the attribute value.
  46. * @see hasAttribute()
  47. */
  48. public function setAttribute($name, $value);
  49. /**
  50. * Returns a value indicating whether the record has an attribute with the specified name.
  51. * @param string $name the name of the attribute
  52. * @return bool whether the record has an attribute with the specified name.
  53. */
  54. public function hasAttribute($name);
  55. /**
  56. * Returns the primary key value(s).
  57. * @param bool $asArray whether to return the primary key value as an array. If true,
  58. * the return value will be an array with attribute names as keys and attribute values as values.
  59. * Note that for composite primary keys, an array will always be returned regardless of this parameter value.
  60. * @return mixed the primary key value. An array (attribute name => attribute value) is returned if the primary key
  61. * is composite or `$asArray` is true. A string is returned otherwise (`null` will be returned if
  62. * the key value is `null`).
  63. */
  64. public function getPrimaryKey($asArray = false);
  65. /**
  66. * Returns the old primary key value(s).
  67. * This refers to the primary key value that is populated into the record
  68. * after executing a find method (e.g. find(), findOne()).
  69. * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
  70. * @param bool $asArray whether to return the primary key value as an array. If true,
  71. * the return value will be an array with column name as key and column value as value.
  72. * If this is `false` (default), a scalar value will be returned for non-composite primary key.
  73. * @property mixed The old primary key value. An array (column name => column value) is
  74. * returned if the primary key is composite. A string is returned otherwise (`null` will be
  75. * returned if the key value is `null`).
  76. * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key
  77. * is composite or `$asArray` is true. A string is returned otherwise (`null` will be returned if
  78. * the key value is `null`).
  79. */
  80. public function getOldPrimaryKey($asArray = false);
  81. /**
  82. * Returns a value indicating whether the given set of attributes represents the primary key for this model.
  83. * @param array $keys the set of attributes to check
  84. * @return bool whether the given set of attributes represents the primary key for this model
  85. */
  86. public static function isPrimaryKey($keys);
  87. /**
  88. * Creates an [[ActiveQueryInterface]] instance for query purpose.
  89. *
  90. * The returned [[ActiveQueryInterface]] instance can be further customized by calling
  91. * methods defined in [[ActiveQueryInterface]] before `one()` or `all()` is called to return
  92. * populated ActiveRecord instances. For example,
  93. *
  94. * ```php
  95. * // find the customer whose ID is 1
  96. * $customer = Customer::find()->where(['id' => 1])->one();
  97. *
  98. * // find all active customers and order them by their age:
  99. * $customers = Customer::find()
  100. * ->where(['status' => 1])
  101. * ->orderBy('age')
  102. * ->all();
  103. * ```
  104. *
  105. * This method is also called by [[BaseActiveRecord::hasOne()]] and [[BaseActiveRecord::hasMany()]] to
  106. * create a relational query.
  107. *
  108. * You may override this method to return a customized query. For example,
  109. *
  110. * ```php
  111. * class Customer extends ActiveRecord
  112. * {
  113. * public static function find()
  114. * {
  115. * // use CustomerQuery instead of the default ActiveQuery
  116. * return new CustomerQuery(get_called_class());
  117. * }
  118. * }
  119. * ```
  120. *
  121. * The following code shows how to apply a default condition for all queries:
  122. *
  123. * ```php
  124. * class Customer extends ActiveRecord
  125. * {
  126. * public static function find()
  127. * {
  128. * return parent::find()->where(['deleted' => false]);
  129. * }
  130. * }
  131. *
  132. * // Use andWhere()/orWhere() to apply the default condition
  133. * // SELECT FROM customer WHERE `deleted`=:deleted AND age>30
  134. * $customers = Customer::find()->andWhere('age>30')->all();
  135. *
  136. * // Use where() to ignore the default condition
  137. * // SELECT FROM customer WHERE age>30
  138. * $customers = Customer::find()->where('age>30')->all();
  139. *
  140. * @return ActiveQueryInterface the newly created [[ActiveQueryInterface]] instance.
  141. */
  142. public static function find();
  143. /**
  144. * Returns a single active record model instance by a primary key or an array of column values.
  145. *
  146. * The method accepts:
  147. *
  148. * - a scalar value (integer or string): query by a single primary key value and return the
  149. * corresponding record (or `null` if not found).
  150. * - a non-associative array: query by a list of primary key values and return the
  151. * first record (or `null` if not found).
  152. * - an associative array of name-value pairs: query by a set of attribute values and return a single record
  153. * matching all of them (or `null` if not found). Note that `['id' => 1, 2]` is treated as a non-associative array.
  154. * Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limited to simple filter conditions.
  155. * - a yii\db\Expression: The expression will be used directly. (@since 2.0.37)
  156. *
  157. * That this method will automatically call the `one()` method and return an [[ActiveRecordInterface|ActiveRecord]]
  158. * instance.
  159. *
  160. * > Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work.
  161. * > If you need to specify more complex conditions, use [[find()]] in combination with [[ActiveQuery::where()|where()]] instead.
  162. *
  163. * See the following code for usage examples:
  164. *
  165. * ```php
  166. * // find a single customer whose primary key value is 10
  167. * $customer = Customer::findOne(10);
  168. *
  169. * // the above code is equivalent to:
  170. * $customer = Customer::find()->where(['id' => 10])->one();
  171. *
  172. * // find the customers whose primary key value is 10, 11 or 12.
  173. * $customers = Customer::findOne([10, 11, 12]);
  174. *
  175. * // the above code is equivalent to:
  176. * $customers = Customer::find()->where(['id' => [10, 11, 12]])->one();
  177. *
  178. * // find the first customer whose age is 30 and whose status is 1
  179. * $customer = Customer::findOne(['age' => 30, 'status' => 1]);
  180. *
  181. * // the above code is equivalent to:
  182. * $customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
  183. * ```
  184. *
  185. * If you need to pass user input to this method, make sure the input value is scalar or in case of
  186. * array condition, make sure the array structure can not be changed from the outside:
  187. *
  188. * ```php
  189. * // yii\web\Controller ensures that $id is scalar
  190. * public function actionView($id)
  191. * {
  192. * $model = Post::findOne($id);
  193. * // ...
  194. * }
  195. *
  196. * // explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
  197. * $model = Post::findOne(['id' => Yii::$app->request->get('id')]);
  198. *
  199. * // do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
  200. * $model = Post::findOne(Yii::$app->request->get('id'));
  201. * ```
  202. *
  203. * @param mixed $condition primary key value or a set of column values
  204. * @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches.
  205. */
  206. public static function findOne($condition);
  207. /**
  208. * Returns a list of active record models that match the specified primary key value(s) or a set of column values.
  209. *
  210. * The method accepts:
  211. *
  212. * - a scalar value (integer or string): query by a single primary key value and return an array containing the
  213. * corresponding record (or an empty array if not found).
  214. * - a non-associative array: query by a list of primary key values and return the
  215. * corresponding records (or an empty array if none was found).
  216. * Note that an empty condition will result in an empty result as it will be interpreted as a search for
  217. * primary keys and not an empty `WHERE` condition.
  218. * - an associative array of name-value pairs: query by a set of attribute values and return an array of records
  219. * matching all of them (or an empty array if none was found). Note that `['id' => 1, 2]` is treated as
  220. * a non-associative array.
  221. * Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limted to simple filter conditions.
  222. * - a yii\db\Expression: The expression will be used directly. (@since 2.0.37)
  223. *
  224. * This method will automatically call the `all()` method and return an array of [[ActiveRecordInterface|ActiveRecord]]
  225. * instances.
  226. *
  227. * > Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work.
  228. * > If you need to specify more complex conditions, use [[find()]] in combination with [[ActiveQuery::where()|where()]] instead.
  229. *
  230. * See the following code for usage examples:
  231. *
  232. * ```php
  233. * // find the customers whose primary key value is 10
  234. * $customers = Customer::findAll(10);
  235. *
  236. * // the above code is equivalent to:
  237. * $customers = Customer::find()->where(['id' => 10])->all();
  238. *
  239. * // find the customers whose primary key value is 10, 11 or 12.
  240. * $customers = Customer::findAll([10, 11, 12]);
  241. *
  242. * // the above code is equivalent to:
  243. * $customers = Customer::find()->where(['id' => [10, 11, 12]])->all();
  244. *
  245. * // find customers whose age is 30 and whose status is 1
  246. * $customers = Customer::findAll(['age' => 30, 'status' => 1]);
  247. *
  248. * // the above code is equivalent to:
  249. * $customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
  250. * ```
  251. *
  252. * If you need to pass user input to this method, make sure the input value is scalar or in case of
  253. * array condition, make sure the array structure can not be changed from the outside:
  254. *
  255. * ```php
  256. * // yii\web\Controller ensures that $id is scalar
  257. * public function actionView($id)
  258. * {
  259. * $model = Post::findOne($id);
  260. * // ...
  261. * }
  262. *
  263. * // explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
  264. * $model = Post::findOne(['id' => Yii::$app->request->get('id')]);
  265. *
  266. * // do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
  267. * $model = Post::findOne(Yii::$app->request->get('id'));
  268. * ```
  269. *
  270. * @param mixed $condition primary key value or a set of column values
  271. * @return array an array of ActiveRecord instance, or an empty array if nothing matches.
  272. */
  273. public static function findAll($condition);
  274. /**
  275. * Updates records using the provided attribute values and conditions.
  276. *
  277. * For example, to change the status to be 1 for all customers whose status is 2:
  278. *
  279. * ```php
  280. * Customer::updateAll(['status' => 1], ['status' => '2']);
  281. * ```
  282. *
  283. * @param array $attributes attribute values (name-value pairs) to be saved for the record.
  284. * Unlike [[update()]] these are not going to be validated.
  285. * @param mixed $condition the condition that matches the records that should get updated.
  286. * Please refer to [[QueryInterface::where()]] on how to specify this parameter.
  287. * An empty condition will match all records.
  288. * @return int the number of rows updated
  289. */
  290. public static function updateAll($attributes, $condition = null);
  291. /**
  292. * Deletes records using the provided conditions.
  293. * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
  294. *
  295. * For example, to delete all customers whose status is 3:
  296. *
  297. * ```php
  298. * Customer::deleteAll([status = 3]);
  299. * ```
  300. *
  301. * @param array $condition the condition that matches the records that should get deleted.
  302. * Please refer to [[QueryInterface::where()]] on how to specify this parameter.
  303. * An empty condition will match all records.
  304. * @return int the number of rows deleted
  305. */
  306. public static function deleteAll($condition = null);
  307. /**
  308. * Saves the current record.
  309. *
  310. * This method will call [[insert()]] when [[getIsNewRecord()|isNewRecord]] is true, or [[update()]]
  311. * when [[getIsNewRecord()|isNewRecord]] is false.
  312. *
  313. * For example, to save a customer record:
  314. *
  315. * ```php
  316. * $customer = new Customer; // or $customer = Customer::findOne($id);
  317. * $customer->name = $name;
  318. * $customer->email = $email;
  319. * $customer->save();
  320. * ```
  321. *
  322. * @param bool $runValidation whether to perform validation (calling [[\yii\base\Model::validate()|validate()]])
  323. * before saving the record. Defaults to `true`. If the validation fails, the record
  324. * will not be saved to the database and this method will return `false`.
  325. * @param array $attributeNames list of attribute names that need to be saved. Defaults to `null`,
  326. * meaning all attributes that are loaded from DB will be saved.
  327. * @return bool whether the saving succeeded (i.e. no validation errors occurred).
  328. */
  329. public function save($runValidation = true, $attributeNames = null);
  330. /**
  331. * Inserts the record into the database using the attribute values of this record.
  332. *
  333. * Usage example:
  334. *
  335. * ```php
  336. * $customer = new Customer;
  337. * $customer->name = $name;
  338. * $customer->email = $email;
  339. * $customer->insert();
  340. * ```
  341. *
  342. * @param bool $runValidation whether to perform validation (calling [[\yii\base\Model::validate()|validate()]])
  343. * before saving the record. Defaults to `true`. If the validation fails, the record
  344. * will not be saved to the database and this method will return `false`.
  345. * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
  346. * meaning all attributes that are loaded from DB will be saved.
  347. * @return bool whether the attributes are valid and the record is inserted successfully.
  348. */
  349. public function insert($runValidation = true, $attributes = null);
  350. /**
  351. * Saves the changes to this active record into the database.
  352. *
  353. * Usage example:
  354. *
  355. * ```php
  356. * $customer = Customer::findOne($id);
  357. * $customer->name = $name;
  358. * $customer->email = $email;
  359. * $customer->update();
  360. * ```
  361. *
  362. * @param bool $runValidation whether to perform validation (calling [[\yii\base\Model::validate()|validate()]])
  363. * before saving the record. Defaults to `true`. If the validation fails, the record
  364. * will not be saved to the database and this method will return `false`.
  365. * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
  366. * meaning all attributes that are loaded from DB will be saved.
  367. * @return int|bool the number of rows affected, or `false` if validation fails
  368. * or updating process is stopped for other reasons.
  369. * Note that it is possible that the number of rows affected is 0, even though the
  370. * update execution is successful.
  371. */
  372. public function update($runValidation = true, $attributeNames = null);
  373. /**
  374. * Deletes the record from the database.
  375. *
  376. * @return int|bool the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  377. * Note that it is possible that the number of rows deleted is 0, even though the deletion execution is successful.
  378. */
  379. public function delete();
  380. /**
  381. * Returns a value indicating whether the current record is new (not saved in the database).
  382. * @return bool whether the record is new and should be inserted when calling [[save()]].
  383. */
  384. public function getIsNewRecord();
  385. /**
  386. * Returns a value indicating whether the given active record is the same as the current one.
  387. * Two [[getIsNewRecord()|new]] records are considered to be not equal.
  388. * @param static $record record to compare to
  389. * @return bool whether the two active records refer to the same row in the same database table.
  390. */
  391. public function equals($record);
  392. /**
  393. * Returns the relation object with the specified name.
  394. * A relation is defined by a getter method which returns an object implementing the [[ActiveQueryInterface]]
  395. * (normally this would be a relational [[ActiveQuery]] object).
  396. * It can be declared in either the ActiveRecord class itself or one of its behaviors.
  397. * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
  398. * @param bool $throwException whether to throw exception if the relation does not exist.
  399. * @return ActiveQueryInterface the relational query object
  400. */
  401. public function getRelation($name, $throwException = true);
  402. /**
  403. * Populates the named relation with the related records.
  404. * Note that this method does not check if the relation exists or not.
  405. * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
  406. * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation.
  407. * @since 2.0.8
  408. */
  409. public function populateRelation($name, $records);
  410. /**
  411. * Establishes the relationship between two records.
  412. *
  413. * The relationship is established by setting the foreign key value(s) in one record
  414. * to be the corresponding primary key value(s) in the other record.
  415. * The record with the foreign key will be saved into database without performing validation.
  416. *
  417. * If the relationship involves a junction table, a new row will be inserted into the
  418. * junction table which contains the primary key values from both records.
  419. *
  420. * This method requires that the primary key value is not `null`.
  421. *
  422. * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
  423. * @param static $model the record to be linked with the current one.
  424. * @param array $extraColumns additional column values to be saved into the junction table.
  425. * This parameter is only meaningful for a relationship involving a junction table
  426. * (i.e., a relation set with [[ActiveQueryInterface::via()]]).
  427. */
  428. public function link($name, $model, $extraColumns = []);
  429. /**
  430. * Destroys the relationship between two records.
  431. *
  432. * The record with the foreign key of the relationship will be deleted if `$delete` is true.
  433. * Otherwise, the foreign key will be set `null` and the record will be saved without validation.
  434. *
  435. * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
  436. * @param static $model the model to be unlinked from the current one.
  437. * @param bool $delete whether to delete the model that contains the foreign key.
  438. * If false, the model's foreign key will be set `null` and saved.
  439. * If true, the model containing the foreign key will be deleted.
  440. */
  441. public function unlink($name, $model, $delete = false);
  442. /**
  443. * Returns the connection used by this AR class.
  444. * @return mixed the database connection used by this AR class.
  445. */
  446. public static function getDb();
  447. }