Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

213 lines
6.9KB

  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. /**
  9. * ActiveQueryTrait implements the common methods and properties for active record query classes.
  10. *
  11. * @author Qiang Xue <qiang.xue@gmail.com>
  12. * @author Carsten Brandt <mail@cebe.cc>
  13. * @since 2.0
  14. */
  15. trait ActiveQueryTrait
  16. {
  17. /**
  18. * @var string the name of the ActiveRecord class.
  19. */
  20. public $modelClass;
  21. /**
  22. * @var array a list of relations that this query should be performed with
  23. */
  24. public $with;
  25. /**
  26. * @var boolean whether to return each record as an array. If false (default), an object
  27. * of [[modelClass]] will be created to represent each record.
  28. */
  29. public $asArray;
  30. /**
  31. * Sets the [[asArray]] property.
  32. * @param boolean $value whether to return the query results in terms of arrays instead of Active Records.
  33. * @return static the query object itself
  34. */
  35. public function asArray($value = true)
  36. {
  37. $this->asArray = $value;
  38. return $this;
  39. }
  40. /**
  41. * Specifies the relations with which this query should be performed.
  42. *
  43. * The parameters to this method can be either one or multiple strings, or a single array
  44. * of relation names and the optional callbacks to customize the relations.
  45. *
  46. * A relation name can refer to a relation defined in [[modelClass]]
  47. * or a sub-relation that stands for a relation of a related record.
  48. * For example, `orders.address` means the `address` relation defined
  49. * in the model class corresponding to the `orders` relation.
  50. *
  51. * The followings are some usage examples:
  52. *
  53. * ~~~
  54. * // find customers together with their orders and country
  55. * Customer::find()->with('orders', 'country')->all();
  56. * // find customers together with their orders and the orders' shipping address
  57. * Customer::find()->with('orders.address')->all();
  58. * // find customers together with their country and orders of status 1
  59. * Customer::find()->with([
  60. * 'orders' => function ($query) {
  61. * $query->andWhere('status = 1');
  62. * },
  63. * 'country',
  64. * ])->all();
  65. * ~~~
  66. *
  67. * You can call `with()` multiple times. Each call will add relations to the existing ones.
  68. * For example, the following two statements are equivalent:
  69. *
  70. * ~~~
  71. * Customer::find()->with('orders', 'country')->all();
  72. * Customer::find()->with('orders')->with('country')->all();
  73. * ~~~
  74. *
  75. * @return static the query object itself
  76. */
  77. public function with()
  78. {
  79. $with = func_get_args();
  80. if (isset($with[0]) && is_array($with[0])) {
  81. // the parameter is given as an array
  82. $with = $with[0];
  83. }
  84. if (empty($this->with)) {
  85. $this->with = $with;
  86. } elseif (!empty($with)) {
  87. foreach ($with as $name => $value) {
  88. if (is_integer($name)) {
  89. // repeating relation is fine as normalizeRelations() handle it well
  90. $this->with[] = $value;
  91. } else {
  92. $this->with[$name] = $value;
  93. }
  94. }
  95. }
  96. return $this;
  97. }
  98. /**
  99. * Converts found rows into model instances
  100. * @param array $rows
  101. * @return array|ActiveRecord[]
  102. */
  103. private function createModels($rows)
  104. {
  105. $models = [];
  106. if ($this->asArray) {
  107. if ($this->indexBy === null) {
  108. return $rows;
  109. }
  110. foreach ($rows as $row) {
  111. if (is_string($this->indexBy)) {
  112. $key = $row[$this->indexBy];
  113. } else {
  114. $key = call_user_func($this->indexBy, $row);
  115. }
  116. $models[$key] = $row;
  117. }
  118. } else {
  119. /* @var $class ActiveRecord */
  120. $class = $this->modelClass;
  121. if ($this->indexBy === null) {
  122. foreach ($rows as $row) {
  123. $model = $class::instantiate($row);
  124. $modelClass = get_class($model);
  125. $modelClass::populateRecord($model, $row);
  126. $models[] = $model;
  127. }
  128. } else {
  129. foreach ($rows as $row) {
  130. $model = $class::instantiate($row);
  131. $modelClass = get_class($model);
  132. $modelClass::populateRecord($model, $row);
  133. if (is_string($this->indexBy)) {
  134. $key = $model->{$this->indexBy};
  135. } else {
  136. $key = call_user_func($this->indexBy, $model);
  137. }
  138. $models[$key] = $model;
  139. }
  140. }
  141. }
  142. return $models;
  143. }
  144. /**
  145. * Finds records corresponding to one or multiple relations and populates them into the primary models.
  146. * @param array $with a list of relations that this query should be performed with. Please
  147. * refer to [[with()]] for details about specifying this parameter.
  148. * @param array|ActiveRecord[] $models the primary models (can be either AR instances or arrays)
  149. */
  150. public function findWith($with, &$models)
  151. {
  152. $primaryModel = new $this->modelClass;
  153. $relations = $this->normalizeRelations($primaryModel, $with);
  154. /* @var $relation ActiveQuery */
  155. foreach ($relations as $name => $relation) {
  156. if ($relation->asArray === null) {
  157. // inherit asArray from primary query
  158. $relation->asArray($this->asArray);
  159. }
  160. $relation->populateRelation($name, $models);
  161. }
  162. }
  163. /**
  164. * @param ActiveRecord $model
  165. * @param array $with
  166. * @return ActiveQueryInterface[]
  167. */
  168. private function normalizeRelations($model, $with)
  169. {
  170. $relations = [];
  171. foreach ($with as $name => $callback) {
  172. if (is_integer($name)) {
  173. $name = $callback;
  174. $callback = null;
  175. }
  176. if (($pos = strpos($name, '.')) !== false) {
  177. // with sub-relations
  178. $childName = substr($name, $pos + 1);
  179. $name = substr($name, 0, $pos);
  180. } else {
  181. $childName = null;
  182. }
  183. if (!isset($relations[$name])) {
  184. $relation = $model->getRelation($name);
  185. $relation->primaryModel = null;
  186. $relations[$name] = $relation;
  187. } else {
  188. $relation = $relations[$name];
  189. }
  190. if (isset($childName)) {
  191. $relation->with[$childName] = $callback;
  192. } elseif ($callback !== null) {
  193. call_user_func($callback, $relation);
  194. }
  195. }
  196. return $relations;
  197. }
  198. }