ActiveRecordInterface.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. *
  156. * That this method will automatically call the `one()` method and return an [[ActiveRecordInterface|ActiveRecord]]
  157. * instance.
  158. *
  159. * > Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work.
  160. * > If you need to specify more complex conditions, use [[find()]] in combination with [[ActiveQuery::where()|where()]] instead.
  161. *
  162. * See the following code for usage examples:
  163. *
  164. * ```php
  165. * // find a single customer whose primary key value is 10
  166. * $customer = Customer::findOne(10);
  167. *
  168. * // the above code is equivalent to:
  169. * $customer = Customer::find()->where(['id' => 10])->one();
  170. *
  171. * // find the customers whose primary key value is 10, 11 or 12.
  172. * $customers = Customer::findOne([10, 11, 12]);
  173. *
  174. * // the above code is equivalent to:
  175. * $customers = Customer::find()->where(['id' => [10, 11, 12]])->one();
  176. *
  177. * // find the first customer whose age is 30 and whose status is 1
  178. * $customer = Customer::findOne(['age' => 30, 'status' => 1]);
  179. *
  180. * // the above code is equivalent to:
  181. * $customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
  182. * ```
  183. *
  184. * If you need to pass user input to this method, make sure the input value is scalar or in case of
  185. * array condition, make sure the array structure can not be changed from the outside:
  186. *
  187. * ```php
  188. * // yii\web\Controller ensures that $id is scalar
  189. * public function actionView($id)
  190. * {
  191. * $model = Post::findOne($id);
  192. * // ...
  193. * }
  194. *
  195. * // explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
  196. * $model = Post::findOne(['id' => Yii::$app->request->get('id')]);
  197. *
  198. * // do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
  199. * $model = Post::findOne(Yii::$app->request->get('id'));
  200. * ```
  201. *
  202. * @param mixed $condition primary key value or a set of column values
  203. * @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches.
  204. */
  205. public static function findOne($condition);
  206. /**
  207. * Returns a list of active record models that match the specified primary key value(s) or a set of column values.
  208. *
  209. * The method accepts:
  210. *
  211. * - a scalar value (integer or string): query by a single primary key value and return an array containing the
  212. * corresponding record (or an empty array if not found).
  213. * - a non-associative array: query by a list of primary key values and return the
  214. * corresponding records (or an empty array if none was found).
  215. * Note that an empty condition will result in an empty result as it will be interpreted as a search for
  216. * primary keys and not an empty `WHERE` condition.
  217. * - an associative array of name-value pairs: query by a set of attribute values and return an array of records
  218. * matching all of them (or an empty array if none was found). Note that `['id' => 1, 2]` is treated as
  219. * a non-associative array.
  220. * Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limted to simple filter conditions.
  221. *
  222. * This method will automatically call the `all()` method and return an array of [[ActiveRecordInterface|ActiveRecord]]
  223. * instances.
  224. *
  225. * > Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work.
  226. * > If you need to specify more complex conditions, use [[find()]] in combination with [[ActiveQuery::where()|where()]] instead.
  227. *
  228. * See the following code for usage examples:
  229. *
  230. * ```php
  231. * // find the customers whose primary key value is 10
  232. * $customers = Customer::findAll(10);
  233. *
  234. * // the above code is equivalent to:
  235. * $customers = Customer::find()->where(['id' => 10])->all();
  236. *
  237. * // find the customers whose primary key value is 10, 11 or 12.
  238. * $customers = Customer::findAll([10, 11, 12]);
  239. *
  240. * // the above code is equivalent to:
  241. * $customers = Customer::find()->where(['id' => [10, 11, 12]])->all();
  242. *
  243. * // find customers whose age is 30 and whose status is 1
  244. * $customers = Customer::findAll(['age' => 30, 'status' => 1]);
  245. *
  246. * // the above code is equivalent to:
  247. * $customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
  248. * ```
  249. *
  250. * If you need to pass user input to this method, make sure the input value is scalar or in case of
  251. * array condition, make sure the array structure can not be changed from the outside:
  252. *
  253. * ```php
  254. * // yii\web\Controller ensures that $id is scalar
  255. * public function actionView($id)
  256. * {
  257. * $model = Post::findOne($id);
  258. * // ...
  259. * }
  260. *
  261. * // explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
  262. * $model = Post::findOne(['id' => Yii::$app->request->get('id')]);
  263. *
  264. * // do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
  265. * $model = Post::findOne(Yii::$app->request->get('id'));
  266. * ```
  267. *
  268. * @param mixed $condition primary key value or a set of column values
  269. * @return array an array of ActiveRecord instance, or an empty array if nothing matches.
  270. */
  271. public static function findAll($condition);
  272. /**
  273. * Updates records using the provided attribute values and conditions.
  274. *
  275. * For example, to change the status to be 1 for all customers whose status is 2:
  276. *
  277. * ```php
  278. * Customer::updateAll(['status' => 1], ['status' => '2']);
  279. * ```
  280. *
  281. * @param array $attributes attribute values (name-value pairs) to be saved for the record.
  282. * Unlike [[update()]] these are not going to be validated.
  283. * @param array $condition the condition that matches the records that should get updated.
  284. * Please refer to [[QueryInterface::where()]] on how to specify this parameter.
  285. * An empty condition will match all records.
  286. * @return int the number of rows updated
  287. */
  288. public static function updateAll($attributes, $condition = null);
  289. /**
  290. * Deletes records using the provided conditions.
  291. * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
  292. *
  293. * For example, to delete all customers whose status is 3:
  294. *
  295. * ```php
  296. * Customer::deleteAll([status = 3]);
  297. * ```
  298. *
  299. * @param array $condition the condition that matches the records that should get deleted.
  300. * Please refer to [[QueryInterface::where()]] on how to specify this parameter.
  301. * An empty condition will match all records.
  302. * @return int the number of rows deleted
  303. */
  304. public static function deleteAll($condition = null);
  305. /**
  306. * Saves the current record.
  307. *
  308. * This method will call [[insert()]] when [[getIsNewRecord()|isNewRecord]] is true, or [[update()]]
  309. * when [[getIsNewRecord()|isNewRecord]] is false.
  310. *
  311. * For example, to save a customer record:
  312. *
  313. * ```php
  314. * $customer = new Customer; // or $customer = Customer::findOne($id);
  315. * $customer->name = $name;
  316. * $customer->email = $email;
  317. * $customer->save();
  318. * ```
  319. *
  320. * @param bool $runValidation whether to perform validation (calling [[\yii\base\Model::validate()|validate()]])
  321. * before saving the record. Defaults to `true`. If the validation fails, the record
  322. * will not be saved to the database and this method will return `false`.
  323. * @param array $attributeNames list of attribute names that need to be saved. Defaults to `null`,
  324. * meaning all attributes that are loaded from DB will be saved.
  325. * @return bool whether the saving succeeded (i.e. no validation errors occurred).
  326. */
  327. public function save($runValidation = true, $attributeNames = null);
  328. /**
  329. * Inserts the record into the database using the attribute values of this record.
  330. *
  331. * Usage example:
  332. *
  333. * ```php
  334. * $customer = new Customer;
  335. * $customer->name = $name;
  336. * $customer->email = $email;
  337. * $customer->insert();
  338. * ```
  339. *
  340. * @param bool $runValidation whether to perform validation (calling [[\yii\base\Model::validate()|validate()]])
  341. * before saving the record. Defaults to `true`. If the validation fails, the record
  342. * will not be saved to the database and this method will return `false`.
  343. * @param array $attributes list of attributes that need to be saved. Defaults to `null`,
  344. * meaning all attributes that are loaded from DB will be saved.
  345. * @return bool whether the attributes are valid and the record is inserted successfully.
  346. */
  347. public function insert($runValidation = true, $attributes = null);
  348. /**
  349. * Saves the changes to this active record into the database.
  350. *
  351. * Usage example:
  352. *
  353. * ```php
  354. * $customer = Customer::findOne($id);
  355. * $customer->name = $name;
  356. * $customer->email = $email;
  357. * $customer->update();
  358. * ```
  359. *
  360. * @param bool $runValidation whether to perform validation (calling [[\yii\base\Model::validate()|validate()]])
  361. * before saving the record. Defaults to `true`. If the validation fails, the record
  362. * will not be saved to the database and this method will return `false`.
  363. * @param array $attributeNames list of attributes that need to be saved. Defaults to `null`,
  364. * meaning all attributes that are loaded from DB will be saved.
  365. * @return int|bool the number of rows affected, or `false` if validation fails
  366. * or updating process is stopped for other reasons.
  367. * Note that it is possible that the number of rows affected is 0, even though the
  368. * update execution is successful.
  369. */
  370. public function update($runValidation = true, $attributeNames = null);
  371. /**
  372. * Deletes the record from the database.
  373. *
  374. * @return int|bool the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  375. * Note that it is possible that the number of rows deleted is 0, even though the deletion execution is successful.
  376. */
  377. public function delete();
  378. /**
  379. * Returns a value indicating whether the current record is new (not saved in the database).
  380. * @return bool whether the record is new and should be inserted when calling [[save()]].
  381. */
  382. public function getIsNewRecord();
  383. /**
  384. * Returns a value indicating whether the given active record is the same as the current one.
  385. * Two [[getIsNewRecord()|new]] records are considered to be not equal.
  386. * @param static $record record to compare to
  387. * @return bool whether the two active records refer to the same row in the same database table.
  388. */
  389. public function equals($record);
  390. /**
  391. * Returns the relation object with the specified name.
  392. * A relation is defined by a getter method which returns an object implementing the [[ActiveQueryInterface]]
  393. * (normally this would be a relational [[ActiveQuery]] object).
  394. * It can be declared in either the ActiveRecord class itself or one of its behaviors.
  395. * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
  396. * @param bool $throwException whether to throw exception if the relation does not exist.
  397. * @return ActiveQueryInterface the relational query object
  398. */
  399. public function getRelation($name, $throwException = true);
  400. /**
  401. * Populates the named relation with the related records.
  402. * Note that this method does not check if the relation exists or not.
  403. * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
  404. * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation.
  405. * @since 2.0.8
  406. */
  407. public function populateRelation($name, $records);
  408. /**
  409. * Establishes the relationship between two records.
  410. *
  411. * The relationship is established by setting the foreign key value(s) in one record
  412. * to be the corresponding primary key value(s) in the other record.
  413. * The record with the foreign key will be saved into database without performing validation.
  414. *
  415. * If the relationship involves a junction table, a new row will be inserted into the
  416. * junction table which contains the primary key values from both records.
  417. *
  418. * This method requires that the primary key value is not `null`.
  419. *
  420. * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
  421. * @param static $model the record to be linked with the current one.
  422. * @param array $extraColumns additional column values to be saved into the junction table.
  423. * This parameter is only meaningful for a relationship involving a junction table
  424. * (i.e., a relation set with [[ActiveQueryInterface::via()]]).
  425. */
  426. public function link($name, $model, $extraColumns = []);
  427. /**
  428. * Destroys the relationship between two records.
  429. *
  430. * The record with the foreign key of the relationship will be deleted if `$delete` is true.
  431. * Otherwise, the foreign key will be set `null` and the record will be saved without validation.
  432. *
  433. * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
  434. * @param static $model the model to be unlinked from the current one.
  435. * @param bool $delete whether to delete the model that contains the foreign key.
  436. * If false, the model's foreign key will be set `null` and saved.
  437. * If true, the model containing the foreign key will be deleted.
  438. */
  439. public function unlink($name, $model, $delete = false);
  440. /**
  441. * Returns the connection used by this AR class.
  442. * @return mixed the database connection used by this AR class.
  443. */
  444. public static function getDb();
  445. }