ActiveQueryTrait.php 6.3 KB

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