選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ActiveQuery.php 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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\InvalidConfigException;
  9. /**
  10. * ActiveQuery represents a DB query associated with an Active Record class.
  11. *
  12. * An ActiveQuery can be a normal query or be used in a relational context.
  13. *
  14. * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
  15. * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
  16. *
  17. * Normal Query
  18. * ------------
  19. *
  20. * ActiveQuery mainly provides the following methods to retrieve the query results:
  21. *
  22. * - [[one()]]: returns a single record populated with the first row of data.
  23. * - [[all()]]: returns all records based on the query results.
  24. * - [[count()]]: returns the number of records.
  25. * - [[sum()]]: returns the sum over the specified column.
  26. * - [[average()]]: returns the average over the specified column.
  27. * - [[min()]]: returns the min over the specified column.
  28. * - [[max()]]: returns the max over the specified column.
  29. * - [[scalar()]]: returns the value of the first column in the first row of the query result.
  30. * - [[column()]]: returns the value of the first column in the query result.
  31. * - [[exists()]]: returns a value indicating whether the query result has data or not.
  32. *
  33. * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
  34. * [[orderBy()]] to customize the query options.
  35. *
  36. * ActiveQuery also provides the following additional query options:
  37. *
  38. * - [[with()]]: list of relations that this query should be performed with.
  39. * - [[joinWith()]]: reuse a relation query definition to add a join to a query.
  40. * - [[indexBy()]]: the name of the column by which the query result should be indexed.
  41. * - [[asArray()]]: whether to return each record as an array.
  42. *
  43. * These options can be configured using methods of the same name. For example:
  44. *
  45. * ```php
  46. * $customers = Customer::find()->with('orders')->asArray()->all();
  47. * ```
  48. *
  49. * Relational query
  50. * ----------------
  51. *
  52. * In relational context ActiveQuery represents a relation between two Active Record classes.
  53. *
  54. * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and
  55. * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
  56. * a getter method which calls one of the above methods and returns the created ActiveQuery object.
  57. *
  58. * A relation is specified by [[link]] which represents the association between columns
  59. * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
  60. *
  61. * If a relation involves a junction table, it may be specified by [[via()]] or [[viaTable()]] method.
  62. * These methods may only be called in a relational context. Same is true for [[inverseOf()]], which
  63. * marks a relation as inverse of another relation and [[onCondition()]] which adds a condition that
  64. * is to be added to relational query join condition.
  65. *
  66. * @author Qiang Xue <qiang.xue@gmail.com>
  67. * @author Carsten Brandt <mail@cebe.cc>
  68. * @since 2.0
  69. */
  70. class ActiveQuery extends Query implements ActiveQueryInterface
  71. {
  72. use ActiveQueryTrait;
  73. use ActiveRelationTrait;
  74. /**
  75. * @event Event an event that is triggered when the query is initialized via [[init()]].
  76. */
  77. const EVENT_INIT = 'init';
  78. /**
  79. * @var string the SQL statement to be executed for retrieving AR records.
  80. * This is set by [[ActiveRecord::findBySql()]].
  81. */
  82. public $sql;
  83. /**
  84. * @var string|array the join condition to be used when this query is used in a relational context.
  85. * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
  86. * Otherwise, the condition will be used in the WHERE part of a query.
  87. * Please refer to [[Query::where()]] on how to specify this parameter.
  88. * @see onCondition()
  89. */
  90. public $on;
  91. /**
  92. * @var array a list of relations that this query should be joined with
  93. */
  94. public $joinWith;
  95. /**
  96. * Constructor.
  97. * @param string $modelClass the model class associated with this query
  98. * @param array $config configurations to be applied to the newly created query object
  99. */
  100. public function __construct($modelClass, $config = [])
  101. {
  102. $this->modelClass = $modelClass;
  103. parent::__construct($config);
  104. }
  105. /**
  106. * Initializes the object.
  107. * This method is called at the end of the constructor. The default implementation will trigger
  108. * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
  109. * to ensure triggering of the event.
  110. */
  111. public function init()
  112. {
  113. parent::init();
  114. $this->trigger(self::EVENT_INIT);
  115. }
  116. /**
  117. * Executes query and returns all results as an array.
  118. * @param Connection $db the DB connection used to create the DB command.
  119. * If null, the DB connection returned by [[modelClass]] will be used.
  120. * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
  121. */
  122. public function all($db = null)
  123. {
  124. return parent::all($db);
  125. }
  126. /**
  127. * @inheritdoc
  128. */
  129. public function prepare($builder)
  130. {
  131. // NOTE: because the same ActiveQuery may be used to build different SQL statements
  132. // (e.g. by ActiveDataProvider, one for count query, the other for row data query,
  133. // it is important to make sure the same ActiveQuery can be used to build SQL statements
  134. // multiple times.
  135. if (!empty($this->joinWith)) {
  136. $this->buildJoinWith();
  137. $this->joinWith = null; // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
  138. }
  139. if (empty($this->from)) {
  140. /* @var $modelClass ActiveRecord */
  141. $modelClass = $this->modelClass;
  142. $tableName = $modelClass::tableName();
  143. $this->from = [$tableName];
  144. }
  145. if (empty($this->select) && !empty($this->join)) {
  146. list(, $alias) = $this->getQueryTableName($this);
  147. $this->select = ["$alias.*"];
  148. }
  149. if ($this->primaryModel === null) {
  150. // eager loading
  151. $query = Query::create($this);
  152. } else {
  153. // lazy loading of a relation
  154. $where = $this->where;
  155. if ($this->via instanceof self) {
  156. // via junction table
  157. $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
  158. $this->filterByModels($viaModels);
  159. } elseif (is_array($this->via)) {
  160. // via relation
  161. /* @var $viaQuery ActiveQuery */
  162. list($viaName, $viaQuery) = $this->via;
  163. if ($viaQuery->multiple) {
  164. $viaModels = $viaQuery->all();
  165. $this->primaryModel->populateRelation($viaName, $viaModels);
  166. } else {
  167. $model = $viaQuery->one();
  168. $this->primaryModel->populateRelation($viaName, $model);
  169. $viaModels = $model === null ? [] : [$model];
  170. }
  171. $this->filterByModels($viaModels);
  172. } else {
  173. $this->filterByModels([$this->primaryModel]);
  174. }
  175. $query = Query::create($this);
  176. $this->where = $where;
  177. }
  178. if (!empty($this->on)) {
  179. $query->andWhere($this->on);
  180. }
  181. return $query;
  182. }
  183. /**
  184. * @inheritdoc
  185. */
  186. public function populate($rows)
  187. {
  188. if (empty($rows)) {
  189. return [];
  190. }
  191. $models = $this->createModels($rows);
  192. if (!empty($this->join) && $this->indexBy === null) {
  193. $models = $this->removeDuplicatedModels($models);
  194. }
  195. if (!empty($this->with)) {
  196. $this->findWith($this->with, $models);
  197. }
  198. if ($this->inverseOf !== null) {
  199. $this->addInverseRelations($models);
  200. }
  201. if (!$this->asArray) {
  202. foreach ($models as $model) {
  203. $model->afterFind();
  204. }
  205. }
  206. return $models;
  207. }
  208. /**
  209. * Removes duplicated models by checking their primary key values.
  210. * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
  211. * @param array $models the models to be checked
  212. * @throws InvalidConfigException if model primary key is empty
  213. * @return array the distinctive models
  214. */
  215. private function removeDuplicatedModels($models)
  216. {
  217. $hash = [];
  218. /* @var $class ActiveRecord */
  219. $class = $this->modelClass;
  220. $pks = $class::primaryKey();
  221. if (count($pks) > 1) {
  222. // composite primary key
  223. foreach ($models as $i => $model) {
  224. $key = [];
  225. foreach ($pks as $pk) {
  226. if (!isset($model[$pk])) {
  227. // do not continue if the primary key is not part of the result set
  228. break 2;
  229. }
  230. $key[] = $model[$pk];
  231. }
  232. $key = serialize($key);
  233. if (isset($hash[$key])) {
  234. unset($models[$i]);
  235. } else {
  236. $hash[$key] = true;
  237. }
  238. }
  239. } elseif (empty($pks)) {
  240. throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
  241. } else {
  242. // single column primary key
  243. $pk = reset($pks);
  244. foreach ($models as $i => $model) {
  245. if (!isset($model[$pk])) {
  246. // do not continue if the primary key is not part of the result set
  247. break;
  248. }
  249. $key = $model[$pk];
  250. if (isset($hash[$key])) {
  251. unset($models[$i]);
  252. } elseif ($key !== null) {
  253. $hash[$key] = true;
  254. }
  255. }
  256. }
  257. return array_values($models);
  258. }
  259. /**
  260. * Executes query and returns a single row of result.
  261. * @param Connection $db the DB connection used to create the DB command.
  262. * If null, the DB connection returned by [[modelClass]] will be used.
  263. * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
  264. * the query result may be either an array or an ActiveRecord object. Null will be returned
  265. * if the query results in nothing.
  266. */
  267. public function one($db = null)
  268. {
  269. $row = parent::one($db);
  270. if ($row !== false) {
  271. $models = $this->populate([$row]);
  272. return reset($models) ?: null;
  273. } else {
  274. return null;
  275. }
  276. }
  277. /**
  278. * Creates a DB command that can be used to execute this query.
  279. * @param Connection $db the DB connection used to create the DB command.
  280. * If null, the DB connection returned by [[modelClass]] will be used.
  281. * @return Command the created DB command instance.
  282. */
  283. public function createCommand($db = null)
  284. {
  285. /* @var $modelClass ActiveRecord */
  286. $modelClass = $this->modelClass;
  287. if ($db === null) {
  288. $db = $modelClass::getDb();
  289. }
  290. if ($this->sql === null) {
  291. list ($sql, $params) = $db->getQueryBuilder()->build($this);
  292. } else {
  293. $sql = $this->sql;
  294. $params = $this->params;
  295. }
  296. return $db->createCommand($sql, $params);
  297. }
  298. /**
  299. * @inheritdoc
  300. */
  301. protected function queryScalar($selectExpression, $db)
  302. {
  303. if ($this->sql === null) {
  304. return parent::queryScalar($selectExpression, $db);
  305. }
  306. /* @var $modelClass ActiveRecord */
  307. $modelClass = $this->modelClass;
  308. if ($db === null) {
  309. $db = $modelClass::getDb();
  310. }
  311. return (new Query)->select([$selectExpression])
  312. ->from(['c' => "({$this->sql})"])
  313. ->params($this->params)
  314. ->createCommand($db)
  315. ->queryScalar();
  316. }
  317. /**
  318. * Joins with the specified relations.
  319. *
  320. * This method allows you to reuse existing relation definitions to perform JOIN queries.
  321. * Based on the definition of the specified relation(s), the method will append one or multiple
  322. * JOIN statements to the current query.
  323. *
  324. * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
  325. * which is equivalent to calling [[with()]] using the specified relations.
  326. *
  327. * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
  328. *
  329. * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
  330. * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
  331. *
  332. * @param string|array $with the relations to be joined. This can either be a string, representing a relation name or
  333. * an array with the following semantics:
  334. *
  335. * - Each array element represents a single relation.
  336. * - You may specify the relation name as the array key and provide an anonymous functions that
  337. * can be used to modify the relation queries on-the-fly as the array value.
  338. * - If a relation query does not need modification, you may use the relation name as the array value.
  339. *
  340. * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
  341. *
  342. * Sub-relations can also be specified, see [[with()]] for the syntax.
  343. *
  344. * In the following you find some examples:
  345. *
  346. * ```php
  347. * // find all orders that contain books, and eager loading "books"
  348. * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
  349. * // find all orders, eager loading "books", and sort the orders and books by the book names.
  350. * Order::find()->joinWith([
  351. * 'books' => function (\yii\db\ActiveQuery $query) {
  352. * $query->orderBy('item.name');
  353. * }
  354. * ])->all();
  355. * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
  356. * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
  357. * ```
  358. *
  359. * The alias syntax is available since version 2.0.7.
  360. *
  361. * @param boolean|array $eagerLoading whether to eager load the relations specified in `$with`.
  362. * When this is a boolean, it applies to all relations specified in `$with`. Use an array
  363. * to explicitly list which relations in `$with` need to be eagerly loaded. Defaults to `true`.
  364. * @param string|array $joinType the join type of the relations specified in `$with`.
  365. * When this is a string, it applies to all relations specified in `$with`. Use an array
  366. * in the format of `relationName => joinType` to specify different join types for different relations.
  367. * @return $this the query object itself
  368. */
  369. public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
  370. {
  371. $relations = [];
  372. foreach ((array) $with as $name => $callback) {
  373. if (is_int($name)) {
  374. $name = $callback;
  375. $callback = null;
  376. }
  377. if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
  378. // relation is defined with an alias, adjust callback to apply alias
  379. list(, $relation, $alias) = $matches;
  380. $name = $relation;
  381. $callback = function ($query) use ($callback, $alias) {
  382. /** @var $query ActiveQuery */
  383. $query->alias($alias);
  384. if ($callback !== null) {
  385. call_user_func($callback, $query);
  386. }
  387. };
  388. }
  389. if ($callback === null) {
  390. $relations[] = $name;
  391. } else {
  392. $relations[$name] = $callback;
  393. }
  394. }
  395. $this->joinWith[] = [$relations, $eagerLoading, $joinType];
  396. return $this;
  397. }
  398. private function buildJoinWith()
  399. {
  400. $join = $this->join;
  401. $this->join = [];
  402. $model = new $this->modelClass;
  403. foreach ($this->joinWith as $config) {
  404. list ($with, $eagerLoading, $joinType) = $config;
  405. $this->joinWithRelations($model, $with, $joinType);
  406. if (is_array($eagerLoading)) {
  407. foreach ($with as $name => $callback) {
  408. if (is_int($name)) {
  409. if (!in_array($callback, $eagerLoading, true)) {
  410. unset($with[$name]);
  411. }
  412. } elseif (!in_array($name, $eagerLoading, true)) {
  413. unset($with[$name]);
  414. }
  415. }
  416. } elseif (!$eagerLoading) {
  417. $with = [];
  418. }
  419. $this->with($with);
  420. }
  421. // remove duplicated joins added by joinWithRelations that may be added
  422. // e.g. when joining a relation and a via relation at the same time
  423. $uniqueJoins = [];
  424. foreach ($this->join as $j) {
  425. $uniqueJoins[serialize($j)] = $j;
  426. }
  427. $this->join = array_values($uniqueJoins);
  428. if (!empty($join)) {
  429. // append explicit join to joinWith()
  430. // https://github.com/yiisoft/yii2/issues/2880
  431. $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
  432. }
  433. }
  434. /**
  435. * Inner joins with the specified relations.
  436. * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
  437. * Please refer to [[joinWith()]] for detailed usage of this method.
  438. * @param string|array $with the relations to be joined with.
  439. * @param boolean|array $eagerLoading whether to eager loading the relations.
  440. * @return $this the query object itself
  441. * @see joinWith()
  442. */
  443. public function innerJoinWith($with, $eagerLoading = true)
  444. {
  445. return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
  446. }
  447. /**
  448. * Modifies the current query by adding join fragments based on the given relations.
  449. * @param ActiveRecord $model the primary model
  450. * @param array $with the relations to be joined
  451. * @param string|array $joinType the join type
  452. */
  453. private function joinWithRelations($model, $with, $joinType)
  454. {
  455. $relations = [];
  456. foreach ($with as $name => $callback) {
  457. if (is_int($name)) {
  458. $name = $callback;
  459. $callback = null;
  460. }
  461. $primaryModel = $model;
  462. $parent = $this;
  463. $prefix = '';
  464. while (($pos = strpos($name, '.')) !== false) {
  465. $childName = substr($name, $pos + 1);
  466. $name = substr($name, 0, $pos);
  467. $fullName = $prefix === '' ? $name : "$prefix.$name";
  468. if (!isset($relations[$fullName])) {
  469. $relations[$fullName] = $relation = $primaryModel->getRelation($name);
  470. $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
  471. } else {
  472. $relation = $relations[$fullName];
  473. }
  474. $primaryModel = new $relation->modelClass;
  475. $parent = $relation;
  476. $prefix = $fullName;
  477. $name = $childName;
  478. }
  479. $fullName = $prefix === '' ? $name : "$prefix.$name";
  480. if (!isset($relations[$fullName])) {
  481. $relations[$fullName] = $relation = $primaryModel->getRelation($name);
  482. if ($callback !== null) {
  483. call_user_func($callback, $relation);
  484. }
  485. if (!empty($relation->joinWith)) {
  486. $relation->buildJoinWith();
  487. }
  488. $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
  489. }
  490. }
  491. }
  492. /**
  493. * Returns the join type based on the given join type parameter and the relation name.
  494. * @param string|array $joinType the given join type(s)
  495. * @param string $name relation name
  496. * @return string the real join type
  497. */
  498. private function getJoinType($joinType, $name)
  499. {
  500. if (is_array($joinType) && isset($joinType[$name])) {
  501. return $joinType[$name];
  502. } else {
  503. return is_string($joinType) ? $joinType : 'INNER JOIN';
  504. }
  505. }
  506. /**
  507. * Returns the table name and the table alias for [[modelClass]].
  508. * @param ActiveQuery $query
  509. * @return array the table name and the table alias.
  510. */
  511. private function getQueryTableName($query)
  512. {
  513. if (empty($query->from)) {
  514. /* @var $modelClass ActiveRecord */
  515. $modelClass = $query->modelClass;
  516. $tableName = $modelClass::tableName();
  517. } else {
  518. $tableName = '';
  519. foreach ($query->from as $alias => $tableName) {
  520. if (is_string($alias)) {
  521. return [$tableName, $alias];
  522. } else {
  523. break;
  524. }
  525. }
  526. }
  527. if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
  528. $alias = $matches[2];
  529. } else {
  530. $alias = $tableName;
  531. }
  532. return [$tableName, $alias];
  533. }
  534. /**
  535. * Joins a parent query with a child query.
  536. * The current query object will be modified accordingly.
  537. * @param ActiveQuery $parent
  538. * @param ActiveQuery $child
  539. * @param string $joinType
  540. */
  541. private function joinWithRelation($parent, $child, $joinType)
  542. {
  543. $via = $child->via;
  544. $child->via = null;
  545. if ($via instanceof ActiveQuery) {
  546. // via table
  547. $this->joinWithRelation($parent, $via, $joinType);
  548. $this->joinWithRelation($via, $child, $joinType);
  549. return;
  550. } elseif (is_array($via)) {
  551. // via relation
  552. $this->joinWithRelation($parent, $via[1], $joinType);
  553. $this->joinWithRelation($via[1], $child, $joinType);
  554. return;
  555. }
  556. list ($parentTable, $parentAlias) = $this->getQueryTableName($parent);
  557. list ($childTable, $childAlias) = $this->getQueryTableName($child);
  558. if (!empty($child->link)) {
  559. if (strpos($parentAlias, '{{') === false) {
  560. $parentAlias = '{{' . $parentAlias . '}}';
  561. }
  562. if (strpos($childAlias, '{{') === false) {
  563. $childAlias = '{{' . $childAlias . '}}';
  564. }
  565. $on = [];
  566. foreach ($child->link as $childColumn => $parentColumn) {
  567. $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
  568. }
  569. $on = implode(' AND ', $on);
  570. if (!empty($child->on)) {
  571. $on = ['and', $on, $child->on];
  572. }
  573. } else {
  574. $on = $child->on;
  575. }
  576. $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
  577. if (!empty($child->where)) {
  578. $this->andWhere($child->where);
  579. }
  580. if (!empty($child->having)) {
  581. $this->andHaving($child->having);
  582. }
  583. if (!empty($child->orderBy)) {
  584. $this->addOrderBy($child->orderBy);
  585. }
  586. if (!empty($child->groupBy)) {
  587. $this->addGroupBy($child->groupBy);
  588. }
  589. if (!empty($child->params)) {
  590. $this->addParams($child->params);
  591. }
  592. if (!empty($child->join)) {
  593. foreach ($child->join as $join) {
  594. $this->join[] = $join;
  595. }
  596. }
  597. if (!empty($child->union)) {
  598. foreach ($child->union as $union) {
  599. $this->union[] = $union;
  600. }
  601. }
  602. }
  603. /**
  604. * Sets the ON condition for a relational query.
  605. * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
  606. * Otherwise, the condition will be used in the WHERE part of a query.
  607. *
  608. * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
  609. *
  610. * ```php
  611. * public function getActiveUsers()
  612. * {
  613. * return $this->hasMany(User::className(), ['id' => 'user_id'])
  614. * ->onCondition(['active' => true]);
  615. * }
  616. * ```
  617. *
  618. * Note that this condition is applied in case of a join as well as when fetching the related records.
  619. * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
  620. * record will cause an error in a non-join-query.
  621. *
  622. * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
  623. * @param array $params the parameters (name => value) to be bound to the query.
  624. * @return $this the query object itself
  625. */
  626. public function onCondition($condition, $params = [])
  627. {
  628. $this->on = $condition;
  629. $this->addParams($params);
  630. return $this;
  631. }
  632. /**
  633. * Adds an additional ON condition to the existing one.
  634. * The new condition and the existing one will be joined using the 'AND' operator.
  635. * @param string|array $condition the new ON condition. Please refer to [[where()]]
  636. * on how to specify this parameter.
  637. * @param array $params the parameters (name => value) to be bound to the query.
  638. * @return $this the query object itself
  639. * @see onCondition()
  640. * @see orOnCondition()
  641. */
  642. public function andOnCondition($condition, $params = [])
  643. {
  644. if ($this->on === null) {
  645. $this->on = $condition;
  646. } else {
  647. $this->on = ['and', $this->on, $condition];
  648. }
  649. $this->addParams($params);
  650. return $this;
  651. }
  652. /**
  653. * Adds an additional ON condition to the existing one.
  654. * The new condition and the existing one will be joined using the 'OR' operator.
  655. * @param string|array $condition the new ON condition. Please refer to [[where()]]
  656. * on how to specify this parameter.
  657. * @param array $params the parameters (name => value) to be bound to the query.
  658. * @return $this the query object itself
  659. * @see onCondition()
  660. * @see andOnCondition()
  661. */
  662. public function orOnCondition($condition, $params = [])
  663. {
  664. if ($this->on === null) {
  665. $this->on = $condition;
  666. } else {
  667. $this->on = ['or', $this->on, $condition];
  668. }
  669. $this->addParams($params);
  670. return $this;
  671. }
  672. /**
  673. * Specifies the junction table for a relational query.
  674. *
  675. * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
  676. *
  677. * ```php
  678. * public function getItems()
  679. * {
  680. * return $this->hasMany(Item::className(), ['id' => 'item_id'])
  681. * ->viaTable('order_item', ['order_id' => 'id']);
  682. * }
  683. * ```
  684. *
  685. * @param string $tableName the name of the junction table.
  686. * @param array $link the link between the junction table and the table associated with [[primaryModel]].
  687. * The keys of the array represent the columns in the junction table, and the values represent the columns
  688. * in the [[primaryModel]] table.
  689. * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
  690. * Its signature should be `function($query)`, where `$query` is the query to be customized.
  691. * @return $this the query object itself
  692. * @see via()
  693. */
  694. public function viaTable($tableName, $link, callable $callable = null)
  695. {
  696. $relation = new ActiveQuery(get_class($this->primaryModel), [
  697. 'from' => [$tableName],
  698. 'link' => $link,
  699. 'multiple' => true,
  700. 'asArray' => true,
  701. ]);
  702. $this->via = $relation;
  703. if ($callable !== null) {
  704. call_user_func($callable, $relation);
  705. }
  706. return $this;
  707. }
  708. /**
  709. * Define an alias for the table defined in [[modelClass]].
  710. *
  711. * This method will adjust [[from]] so that an already defined alias will be overwritten.
  712. * If none was defined, [[from]] will be populated with the given alias.
  713. *
  714. * @param string $alias the table alias.
  715. * @return $this the query object itself
  716. * @since 2.0.7
  717. */
  718. public function alias($alias)
  719. {
  720. if (empty($this->from) || count($this->from) < 2) {
  721. list($tableName, ) = $this->getQueryTableName($this);
  722. $this->from = [$alias => $tableName];
  723. } else {
  724. /* @var $modelClass ActiveRecord */
  725. $modelClass = $this->modelClass;
  726. $tableName = $modelClass::tableName();
  727. foreach ($this->from as $key => $table) {
  728. if ($table === $tableName) {
  729. unset($this->from[$key]);
  730. $this->from[$alias] = $tableName;
  731. }
  732. }
  733. }
  734. return $this;
  735. }
  736. }