ActiveQuery.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. /**
  3. * @author Qiang Xue <[email protected]>
  4. * @link http://www.yiiframework.com/
  5. * @copyright Copyright (c) 2008 Yii Software LLC
  6. * @license http://www.yiiframework.com/license/
  7. */
  8. namespace yii\db;
  9. /**
  10. * ActiveQuery represents a DB query associated with an Active Record class.
  11. *
  12. * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
  13. *
  14. * ActiveQuery mainly provides the following methods to retrieve the query results:
  15. *
  16. * - [[one()]]: returns a single record populated with the first row of data.
  17. * - [[all()]]: returns all records based on the query results.
  18. * - [[count()]]: returns the number of records.
  19. * - [[sum()]]: returns the sum over the specified column.
  20. * - [[average()]]: returns the average over the specified column.
  21. * - [[min()]]: returns the min over the specified column.
  22. * - [[max()]]: returns the max over the specified column.
  23. * - [[scalar()]]: returns the value of the first column in the first row of the query result.
  24. * - [[column()]]: returns the value of the first column in the query result.
  25. * - [[exists()]]: returns a value indicating whether the query result has data or not.
  26. *
  27. * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
  28. * [[orderBy()]] to customize the query options.
  29. *
  30. * ActiveQuery also provides the following additional query options:
  31. *
  32. * - [[with()]]: list of relations that this query should be performed with.
  33. * - [[indexBy()]]: the name of the column by which the query result should be indexed.
  34. * - [[asArray()]]: whether to return each record as an array.
  35. *
  36. * These options can be configured using methods of the same name. For example:
  37. *
  38. * ~~~
  39. * $customers = Customer::find()->with('orders')->asArray()->all();
  40. * ~~~
  41. *
  42. * @author Qiang Xue <[email protected]>
  43. * @author Carsten Brandt <[email protected]>
  44. * @since 2.0
  45. */
  46. class ActiveQuery extends Query implements ActiveQueryInterface
  47. {
  48. use ActiveQueryTrait;
  49. /**
  50. * @var string the SQL statement to be executed for retrieving AR records.
  51. * This is set by [[ActiveRecord::findBySql()]].
  52. */
  53. public $sql;
  54. /**
  55. * Executes query and returns all results as an array.
  56. * @param Connection $db the DB connection used to create the DB command.
  57. * If null, the DB connection returned by [[modelClass]] will be used.
  58. * @return array the query results. If the query results in nothing, an empty array will be returned.
  59. */
  60. public function all($db = null)
  61. {
  62. $command = $this->createCommand($db);
  63. $rows = $command->queryAll();
  64. if (!empty($rows)) {
  65. $models = $this->createModels($rows);
  66. if (!empty($this->join) && $this->indexBy === null) {
  67. $models = $this->removeDuplicatedModels($models);
  68. }
  69. if (!empty($this->with)) {
  70. $this->findWith($this->with, $models);
  71. }
  72. if (!$this->asArray) {
  73. foreach($models as $model) {
  74. $model->afterFind();
  75. }
  76. }
  77. return $models;
  78. } else {
  79. return [];
  80. }
  81. }
  82. /**
  83. * Removes duplicated models by checking their primary key values.
  84. * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
  85. * @param array $models the models to be checked
  86. * @return array the distinctive models
  87. */
  88. private function removeDuplicatedModels($models)
  89. {
  90. $hash = [];
  91. /** @var ActiveRecord $class */
  92. $class = $this->modelClass;
  93. $pks = $class::primaryKey();
  94. if (count($pks) > 1) {
  95. foreach ($models as $i => $model) {
  96. $key = [];
  97. foreach ($pks as $pk) {
  98. $key[] = $model[$pk];
  99. }
  100. $key = serialize($key);
  101. if (isset($hash[$key])) {
  102. unset($models[$i]);
  103. } else {
  104. $hash[$key] = true;
  105. }
  106. }
  107. } else {
  108. $pk = reset($pks);
  109. foreach ($models as $i => $model) {
  110. $key = $model[$pk];
  111. if (isset($hash[$key])) {
  112. unset($models[$i]);
  113. } else {
  114. $hash[$key] = true;
  115. }
  116. }
  117. }
  118. return array_values($models);
  119. }
  120. /**
  121. * Executes query and returns a single row of result.
  122. * @param Connection $db the DB connection used to create the DB command.
  123. * If null, the DB connection returned by [[modelClass]] will be used.
  124. * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
  125. * the query result may be either an array or an ActiveRecord object. Null will be returned
  126. * if the query results in nothing.
  127. */
  128. public function one($db = null)
  129. {
  130. $command = $this->createCommand($db);
  131. $row = $command->queryOne();
  132. if ($row !== false) {
  133. if ($this->asArray) {
  134. $model = $row;
  135. } else {
  136. /** @var ActiveRecord $class */
  137. $class = $this->modelClass;
  138. $model = $class::create($row);
  139. }
  140. if (!empty($this->with)) {
  141. $models = [$model];
  142. $this->findWith($this->with, $models);
  143. $model = $models[0];
  144. }
  145. if (!$this->asArray) {
  146. $model->afterFind();
  147. }
  148. return $model;
  149. } else {
  150. return null;
  151. }
  152. }
  153. /**
  154. * Creates a DB command that can be used to execute this query.
  155. * @param Connection $db the DB connection used to create the DB command.
  156. * If null, the DB connection returned by [[modelClass]] will be used.
  157. * @return Command the created DB command instance.
  158. */
  159. public function createCommand($db = null)
  160. {
  161. /** @var ActiveRecord $modelClass */
  162. $modelClass = $this->modelClass;
  163. if ($db === null) {
  164. $db = $modelClass::getDb();
  165. }
  166. if ($this->sql === null) {
  167. $select = $this->select;
  168. $from = $this->from;
  169. if ($this->from === null) {
  170. $tableName = $modelClass::tableName();
  171. if ($this->select === null && !empty($this->join)) {
  172. $this->select = ["$tableName.*"];
  173. }
  174. $this->from = [$tableName];
  175. }
  176. list ($sql, $params) = $db->getQueryBuilder()->build($this);
  177. $this->select = $select;
  178. $this->from = $from;
  179. } else {
  180. $sql = $this->sql;
  181. $params = $this->params;
  182. }
  183. return $db->createCommand($sql, $params);
  184. }
  185. /**
  186. * Joins with the specified relations.
  187. *
  188. * This method allows you to reuse existing relation definitions to perform JOIN queries.
  189. * Based on the definition of the specified relation(s), the method will append one or multiple
  190. * JOIN statements to the current query.
  191. *
  192. * If the `$eagerLoading` parameter is true, the method will also eager loading the specified relations,
  193. * which is equivalent to calling [[with()]] using the specified relations.
  194. *
  195. * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
  196. *
  197. * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
  198. * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
  199. *
  200. * @param array $with the relations to be joined. Each array element represents a single relation.
  201. * The array keys are relation names, and the array values are the corresponding anonymous functions that
  202. * can be used to modify the relation queries on-the-fly. If a relation query does not need modification,
  203. * you may use the relation name as the array value. Sub-relations can also be specified (see [[with()]]).
  204. * For example,
  205. *
  206. * ```php
  207. * // find all orders that contain books, and eager loading "books"
  208. * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
  209. * // find all orders, eager loading "books", and sort the orders and books by the book names.
  210. * Order::find()->joinWith([
  211. * 'books' => function ($query) {
  212. * $query->orderBy('tbl_item.name');
  213. * }
  214. * ])->all();
  215. * ```
  216. *
  217. * @param boolean|array $eagerLoading whether to eager load the relations specified in `$with`.
  218. * When this is a boolean, it applies to all relations specified in `$with`. Use an array
  219. * to explicitly list which relations in `$with` need to be eagerly loaded.
  220. * @param string|array $joinType the join type of the relations specified in `$with`.
  221. * When this is a string, it applies to all relations specified in `$with`. Use an array
  222. * in the format of `relationName => joinType` to specify different join types for different relations.
  223. * @return static the query object itself
  224. */
  225. public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
  226. {
  227. $with = (array)$with;
  228. $this->joinWithRelations(new $this->modelClass, $with, $joinType);
  229. if (is_array($eagerLoading)) {
  230. foreach ($with as $name => $callback) {
  231. if (is_integer($name)) {
  232. if (!in_array($callback, $eagerLoading, true)) {
  233. unset($with[$name]);
  234. }
  235. } elseif (!in_array($name, $eagerLoading, true)) {
  236. unset($with[$name]);
  237. }
  238. }
  239. } elseif (!$eagerLoading) {
  240. $with = [];
  241. }
  242. return $this->with($with);
  243. }
  244. /**
  245. * Inner joins with the specified relations.
  246. * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
  247. * Please refer to [[joinWith()]] for detailed usage of this method.
  248. * @param array $with the relations to be joined with
  249. * @param boolean|array $eagerLoading whether to eager loading the relations
  250. * @return static the query object itself
  251. * @see joinWith()
  252. */
  253. public function innerJoinWith($with, $eagerLoading = true)
  254. {
  255. return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
  256. }
  257. /**
  258. * Modifies the current query by adding join fragments based on the given relations.
  259. * @param ActiveRecord $model the primary model
  260. * @param array $with the relations to be joined
  261. * @param string|array $joinType the join type
  262. */
  263. private function joinWithRelations($model, $with, $joinType)
  264. {
  265. $relations = [];
  266. foreach ($with as $name => $callback) {
  267. if (is_integer($name)) {
  268. $name = $callback;
  269. $callback = null;
  270. }
  271. $primaryModel = $model;
  272. $parent = $this;
  273. $prefix = '';
  274. while (($pos = strpos($name, '.')) !== false) {
  275. $childName = substr($name, $pos + 1);
  276. $name = substr($name, 0, $pos);
  277. $fullName = $prefix === '' ? $name : "$prefix.$name";
  278. if (!isset($relations[$fullName])) {
  279. $relations[$fullName] = $relation = $primaryModel->getRelation($name);
  280. $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
  281. } else {
  282. $relation = $relations[$fullName];
  283. }
  284. $primaryModel = new $relation->modelClass;
  285. $parent = $relation;
  286. $prefix = $fullName;
  287. $name = $childName;
  288. }
  289. $fullName = $prefix === '' ? $name : "$prefix.$name";
  290. if (!isset($relations[$fullName])) {
  291. $relations[$fullName] = $relation = $primaryModel->getRelation($name);
  292. if ($callback !== null) {
  293. call_user_func($callback, $relation);
  294. }
  295. $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
  296. }
  297. }
  298. }
  299. /**
  300. * Returns the join type based on the given join type parameter and the relation name.
  301. * @param string|array $joinType the given join type(s)
  302. * @param string $name relation name
  303. * @return string the real join type
  304. */
  305. private function getJoinType($joinType, $name)
  306. {
  307. if (is_array($joinType) && isset($joinType[$name])) {
  308. return $joinType[$name];
  309. } else {
  310. return is_string($joinType) ? $joinType : 'INNER JOIN';
  311. }
  312. }
  313. /**
  314. * Returns the table name and the table alias for [[modelClass]].
  315. * @param ActiveQuery $query
  316. * @return array the table name and the table alias.
  317. */
  318. private function getQueryTableName($query)
  319. {
  320. if (empty($query->from)) {
  321. /** @var ActiveRecord $modelClass */
  322. $modelClass = $query->modelClass;
  323. $tableName = $modelClass::tableName();
  324. } else {
  325. $tableName = reset($query->from);
  326. }
  327. if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
  328. $alias = $matches[2];
  329. } else {
  330. $alias = $tableName;
  331. }
  332. return [$tableName, $alias];
  333. }
  334. /**
  335. * Joins a parent query with a child query.
  336. * The current query object will be modified accordingly.
  337. * @param ActiveQuery $parent
  338. * @param ActiveRelation $child
  339. * @param string $joinType
  340. */
  341. private function joinWithRelation($parent, $child, $joinType)
  342. {
  343. $via = $child->via;
  344. $child->via = null;
  345. if ($via instanceof ActiveRelation) {
  346. // via table
  347. $this->joinWithRelation($parent, $via, $joinType);
  348. $this->joinWithRelation($via, $child, $joinType);
  349. return;
  350. } elseif (is_array($via)) {
  351. // via relation
  352. $this->joinWithRelation($parent, $via[1], $joinType);
  353. $this->joinWithRelation($via[1], $child, $joinType);
  354. return;
  355. }
  356. list ($parentTable, $parentAlias) = $this->getQueryTableName($parent);
  357. list ($childTable, $childAlias) = $this->getQueryTableName($child);
  358. if (!empty($child->link)) {
  359. if (strpos($parentAlias, '{{') === false) {
  360. $parentAlias = '{{' . $parentAlias . '}}';
  361. }
  362. if (strpos($childAlias, '{{') === false) {
  363. $childAlias = '{{' . $childAlias . '}}';
  364. }
  365. $on = [];
  366. foreach ($child->link as $childColumn => $parentColumn) {
  367. $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
  368. }
  369. $on = implode(' AND ', $on);
  370. if (!empty($child->on)) {
  371. $on = ['and', $on, $child->on];
  372. }
  373. } else {
  374. $on = $child->on;
  375. }
  376. $this->join($joinType, $childTable, $on);
  377. if (!empty($child->where)) {
  378. $this->andWhere($child->where);
  379. }
  380. if (!empty($child->having)) {
  381. $this->andHaving($child->having);
  382. }
  383. if (!empty($child->orderBy)) {
  384. $this->addOrderBy($child->orderBy);
  385. }
  386. if (!empty($child->groupBy)) {
  387. $this->addGroupBy($child->groupBy);
  388. }
  389. if (!empty($child->params)) {
  390. $this->addParams($child->params);
  391. }
  392. if (!empty($child->join)) {
  393. foreach ($child->join as $join) {
  394. $this->join[] = $join;
  395. }
  396. }
  397. if (!empty($child->union)) {
  398. foreach ($child->union as $union) {
  399. $this->union[] = $union;
  400. }
  401. }
  402. }
  403. }