ActiveQuery.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. $this->from = [$this->getPrimaryTableName()];
  141. }
  142. if (empty($this->select) && !empty($this->join)) {
  143. list(, $alias) = $this->getTableNameAndAlias();
  144. $this->select = ["$alias.*"];
  145. }
  146. if ($this->primaryModel === null) {
  147. // eager loading
  148. $query = Query::create($this);
  149. } else {
  150. // lazy loading of a relation
  151. $where = $this->where;
  152. if ($this->via instanceof self) {
  153. // via junction table
  154. $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
  155. $this->filterByModels($viaModels);
  156. } elseif (is_array($this->via)) {
  157. // via relation
  158. /* @var $viaQuery ActiveQuery */
  159. list($viaName, $viaQuery, $viaCallableUsed) = $this->via;
  160. if ($viaQuery->multiple) {
  161. if ($viaCallableUsed) {
  162. $viaModels = $viaQuery->all();
  163. } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
  164. $viaModels = $this->primaryModel->$viaName;
  165. } else {
  166. $viaModels = $viaQuery->all();
  167. $this->primaryModel->populateRelation($viaName, $viaModels);
  168. }
  169. } else {
  170. if ($viaCallableUsed) {
  171. $model = $viaQuery->one();
  172. } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
  173. $model = $this->primaryModel->$viaName;
  174. } else {
  175. $model = $viaQuery->one();
  176. $this->primaryModel->populateRelation($viaName, $model);
  177. }
  178. $viaModels = $model === null ? [] : [$model];
  179. }
  180. $this->filterByModels($viaModels);
  181. } else {
  182. $this->filterByModels([$this->primaryModel]);
  183. }
  184. $query = Query::create($this);
  185. $this->where = $where;
  186. }
  187. if (!empty($this->on)) {
  188. $query->andWhere($this->on);
  189. }
  190. return $query;
  191. }
  192. /**
  193. * {@inheritdoc}
  194. */
  195. public function populate($rows)
  196. {
  197. if (empty($rows)) {
  198. return [];
  199. }
  200. $models = $this->createModels($rows);
  201. if (!empty($this->join) && $this->indexBy === null) {
  202. $models = $this->removeDuplicatedModels($models);
  203. }
  204. if (!empty($this->with)) {
  205. $this->findWith($this->with, $models);
  206. }
  207. if ($this->inverseOf !== null) {
  208. $this->addInverseRelations($models);
  209. }
  210. if (!$this->asArray) {
  211. foreach ($models as $model) {
  212. $model->afterFind();
  213. }
  214. }
  215. return parent::populate($models);
  216. }
  217. /**
  218. * Removes duplicated models by checking their primary key values.
  219. * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
  220. * @param array $models the models to be checked
  221. * @throws InvalidConfigException if model primary key is empty
  222. * @return array the distinctive models
  223. */
  224. private function removeDuplicatedModels($models)
  225. {
  226. $hash = [];
  227. /* @var $class ActiveRecord */
  228. $class = $this->modelClass;
  229. $pks = $class::primaryKey();
  230. if (count($pks) > 1) {
  231. // composite primary key
  232. foreach ($models as $i => $model) {
  233. $key = [];
  234. foreach ($pks as $pk) {
  235. if (!isset($model[$pk])) {
  236. // do not continue if the primary key is not part of the result set
  237. break 2;
  238. }
  239. $key[] = $model[$pk];
  240. }
  241. $key = serialize($key);
  242. if (isset($hash[$key])) {
  243. unset($models[$i]);
  244. } else {
  245. $hash[$key] = true;
  246. }
  247. }
  248. } elseif (empty($pks)) {
  249. throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
  250. } else {
  251. // single column primary key
  252. $pk = reset($pks);
  253. foreach ($models as $i => $model) {
  254. if (!isset($model[$pk])) {
  255. // do not continue if the primary key is not part of the result set
  256. break;
  257. }
  258. $key = $model[$pk];
  259. if (isset($hash[$key])) {
  260. unset($models[$i]);
  261. } elseif ($key !== null) {
  262. $hash[$key] = true;
  263. }
  264. }
  265. }
  266. return array_values($models);
  267. }
  268. /**
  269. * Executes query and returns a single row of result.
  270. * @param Connection|null $db the DB connection used to create the DB command.
  271. * If `null`, the DB connection returned by [[modelClass]] will be used.
  272. * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
  273. * the query result may be either an array or an ActiveRecord object. `null` will be returned
  274. * if the query results in nothing.
  275. */
  276. public function one($db = null)
  277. {
  278. $row = parent::one($db);
  279. if ($row !== false) {
  280. $models = $this->populate([$row]);
  281. return reset($models) ?: null;
  282. }
  283. return null;
  284. }
  285. /**
  286. * Creates a DB command that can be used to execute this query.
  287. * @param Connection|null $db the DB connection used to create the DB command.
  288. * If `null`, the DB connection returned by [[modelClass]] will be used.
  289. * @return Command the created DB command instance.
  290. */
  291. public function createCommand($db = null)
  292. {
  293. /* @var $modelClass ActiveRecord */
  294. $modelClass = $this->modelClass;
  295. if ($db === null) {
  296. $db = $modelClass::getDb();
  297. }
  298. if ($this->sql === null) {
  299. list($sql, $params) = $db->getQueryBuilder()->build($this);
  300. } else {
  301. $sql = $this->sql;
  302. $params = $this->params;
  303. }
  304. $command = $db->createCommand($sql, $params);
  305. $this->setCommandCache($command);
  306. return $command;
  307. }
  308. /**
  309. * {@inheritdoc}
  310. */
  311. protected function queryScalar($selectExpression, $db)
  312. {
  313. /* @var $modelClass ActiveRecord */
  314. $modelClass = $this->modelClass;
  315. if ($db === null) {
  316. $db = $modelClass::getDb();
  317. }
  318. if ($this->sql === null) {
  319. return parent::queryScalar($selectExpression, $db);
  320. }
  321. $command = (new Query())->select([$selectExpression])
  322. ->from(['c' => "({$this->sql})"])
  323. ->params($this->params)
  324. ->createCommand($db);
  325. $this->setCommandCache($command);
  326. return $command->queryScalar();
  327. }
  328. /**
  329. * Joins with the specified relations.
  330. *
  331. * This method allows you to reuse existing relation definitions to perform JOIN queries.
  332. * Based on the definition of the specified relation(s), the method will append one or multiple
  333. * JOIN statements to the current query.
  334. *
  335. * If the `$eagerLoading` parameter is true, the method will also perform eager loading for the specified relations,
  336. * which is equivalent to calling [[with()]] using the specified relations.
  337. *
  338. * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
  339. *
  340. * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
  341. * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
  342. *
  343. * @param string|array $with the relations to be joined. This can either be a string, representing a relation name or
  344. * an array with the following semantics:
  345. *
  346. * - Each array element represents a single relation.
  347. * - You may specify the relation name as the array key and provide an anonymous functions that
  348. * can be used to modify the relation queries on-the-fly as the array value.
  349. * - If a relation query does not need modification, you may use the relation name as the array value.
  350. *
  351. * The relation name may optionally contain an alias for the relation table (e.g. `books b`).
  352. *
  353. * Sub-relations can also be specified, see [[with()]] for the syntax.
  354. *
  355. * In the following you find some examples:
  356. *
  357. * ```php
  358. * // find all orders that contain books, and eager loading "books"
  359. * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
  360. * // find all orders, eager loading "books", and sort the orders and books by the book names.
  361. * Order::find()->joinWith([
  362. * 'books' => function (\yii\db\ActiveQuery $query) {
  363. * $query->orderBy('item.name');
  364. * }
  365. * ])->all();
  366. * // find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
  367. * Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();
  368. * ```
  369. *
  370. * The alias syntax is available since version 2.0.7.
  371. *
  372. * @param bool|array $eagerLoading whether to eager load the relations
  373. * specified in `$with`. When this is a boolean, it applies to all
  374. * relations specified in `$with`. Use an array to explicitly list which
  375. * relations in `$with` need to be eagerly loaded. Note, that this does
  376. * not mean, that the relations are populated from the query result. An
  377. * extra query will still be performed to bring in the related data.
  378. * Defaults to `true`.
  379. * @param string|array $joinType the join type of the relations specified in `$with`.
  380. * When this is a string, it applies to all relations specified in `$with`. Use an array
  381. * in the format of `relationName => joinType` to specify different join types for different relations.
  382. * @return $this the query object itself
  383. */
  384. public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
  385. {
  386. $relations = [];
  387. foreach ((array) $with as $name => $callback) {
  388. if (is_int($name)) {
  389. $name = $callback;
  390. $callback = null;
  391. }
  392. if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
  393. // relation is defined with an alias, adjust callback to apply alias
  394. list(, $relation, $alias) = $matches;
  395. $name = $relation;
  396. $callback = function ($query) use ($callback, $alias) {
  397. /* @var $query ActiveQuery */
  398. $query->alias($alias);
  399. if ($callback !== null) {
  400. call_user_func($callback, $query);
  401. }
  402. };
  403. }
  404. if ($callback === null) {
  405. $relations[] = $name;
  406. } else {
  407. $relations[$name] = $callback;
  408. }
  409. }
  410. $this->joinWith[] = [$relations, $eagerLoading, $joinType];
  411. return $this;
  412. }
  413. private function buildJoinWith()
  414. {
  415. $join = $this->join;
  416. $this->join = [];
  417. /* @var $modelClass ActiveRecordInterface */
  418. $modelClass = $this->modelClass;
  419. $model = $modelClass::instance();
  420. foreach ($this->joinWith as $config) {
  421. list($with, $eagerLoading, $joinType) = $config;
  422. $this->joinWithRelations($model, $with, $joinType);
  423. if (is_array($eagerLoading)) {
  424. foreach ($with as $name => $callback) {
  425. if (is_int($name)) {
  426. if (!in_array($callback, $eagerLoading, true)) {
  427. unset($with[$name]);
  428. }
  429. } elseif (!in_array($name, $eagerLoading, true)) {
  430. unset($with[$name]);
  431. }
  432. }
  433. } elseif (!$eagerLoading) {
  434. $with = [];
  435. }
  436. $this->with($with);
  437. }
  438. // remove duplicated joins added by joinWithRelations that may be added
  439. // e.g. when joining a relation and a via relation at the same time
  440. $uniqueJoins = [];
  441. foreach ($this->join as $j) {
  442. $uniqueJoins[serialize($j)] = $j;
  443. }
  444. $this->join = array_values($uniqueJoins);
  445. if (!empty($join)) {
  446. // append explicit join to joinWith()
  447. // https://github.com/yiisoft/yii2/issues/2880
  448. $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
  449. }
  450. }
  451. /**
  452. * Inner joins with the specified relations.
  453. * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
  454. * Please refer to [[joinWith()]] for detailed usage of this method.
  455. * @param string|array $with the relations to be joined with.
  456. * @param bool|array $eagerLoading whether to eager load the relations.
  457. * Note, that this does not mean, that the relations are populated from the
  458. * query result. An extra query will still be performed to bring in the
  459. * related data.
  460. * @return $this the query object itself
  461. * @see joinWith()
  462. */
  463. public function innerJoinWith($with, $eagerLoading = true)
  464. {
  465. return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
  466. }
  467. /**
  468. * Modifies the current query by adding join fragments based on the given relations.
  469. * @param ActiveRecord $model the primary model
  470. * @param array $with the relations to be joined
  471. * @param string|array $joinType the join type
  472. */
  473. private function joinWithRelations($model, $with, $joinType)
  474. {
  475. $relations = [];
  476. foreach ($with as $name => $callback) {
  477. if (is_int($name)) {
  478. $name = $callback;
  479. $callback = null;
  480. }
  481. $primaryModel = $model;
  482. $parent = $this;
  483. $prefix = '';
  484. while (($pos = strpos($name, '.')) !== false) {
  485. $childName = substr($name, $pos + 1);
  486. $name = substr($name, 0, $pos);
  487. $fullName = $prefix === '' ? $name : "$prefix.$name";
  488. if (!isset($relations[$fullName])) {
  489. $relations[$fullName] = $relation = $primaryModel->getRelation($name);
  490. $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
  491. } else {
  492. $relation = $relations[$fullName];
  493. }
  494. /* @var $relationModelClass ActiveRecordInterface */
  495. $relationModelClass = $relation->modelClass;
  496. $primaryModel = $relationModelClass::instance();
  497. $parent = $relation;
  498. $prefix = $fullName;
  499. $name = $childName;
  500. }
  501. $fullName = $prefix === '' ? $name : "$prefix.$name";
  502. if (!isset($relations[$fullName])) {
  503. $relations[$fullName] = $relation = $primaryModel->getRelation($name);
  504. if ($callback !== null) {
  505. call_user_func($callback, $relation);
  506. }
  507. if (!empty($relation->joinWith)) {
  508. $relation->buildJoinWith();
  509. }
  510. $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
  511. }
  512. }
  513. }
  514. /**
  515. * Returns the join type based on the given join type parameter and the relation name.
  516. * @param string|array $joinType the given join type(s)
  517. * @param string $name relation name
  518. * @return string the real join type
  519. */
  520. private function getJoinType($joinType, $name)
  521. {
  522. if (is_array($joinType) && isset($joinType[$name])) {
  523. return $joinType[$name];
  524. }
  525. return is_string($joinType) ? $joinType : 'INNER JOIN';
  526. }
  527. /**
  528. * Returns the table name and the table alias for [[modelClass]].
  529. * @return array the table name and the table alias.
  530. * @since 2.0.16
  531. */
  532. protected function getTableNameAndAlias()
  533. {
  534. if (empty($this->from)) {
  535. $tableName = $this->getPrimaryTableName();
  536. } else {
  537. $tableName = '';
  538. // if the first entry in "from" is an alias-tablename-pair return it directly
  539. foreach ($this->from as $alias => $tableName) {
  540. if (is_string($alias)) {
  541. return [$tableName, $alias];
  542. }
  543. break;
  544. }
  545. }
  546. if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
  547. $alias = $matches[2];
  548. } else {
  549. $alias = $tableName;
  550. }
  551. return [$tableName, $alias];
  552. }
  553. /**
  554. * Joins a parent query with a child query.
  555. * The current query object will be modified accordingly.
  556. * @param ActiveQuery $parent
  557. * @param ActiveQuery $child
  558. * @param string $joinType
  559. */
  560. private function joinWithRelation($parent, $child, $joinType)
  561. {
  562. $via = $child->via;
  563. $child->via = null;
  564. if ($via instanceof self) {
  565. // via table
  566. $this->joinWithRelation($parent, $via, $joinType);
  567. $this->joinWithRelation($via, $child, $joinType);
  568. return;
  569. } elseif (is_array($via)) {
  570. // via relation
  571. $this->joinWithRelation($parent, $via[1], $joinType);
  572. $this->joinWithRelation($via[1], $child, $joinType);
  573. return;
  574. }
  575. list($parentTable, $parentAlias) = $parent->getTableNameAndAlias();
  576. list($childTable, $childAlias) = $child->getTableNameAndAlias();
  577. if (!empty($child->link)) {
  578. if (strpos($parentAlias, '{{') === false) {
  579. $parentAlias = '{{' . $parentAlias . '}}';
  580. }
  581. if (strpos($childAlias, '{{') === false) {
  582. $childAlias = '{{' . $childAlias . '}}';
  583. }
  584. $on = [];
  585. foreach ($child->link as $childColumn => $parentColumn) {
  586. $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
  587. }
  588. $on = implode(' AND ', $on);
  589. if (!empty($child->on)) {
  590. $on = ['and', $on, $child->on];
  591. }
  592. } else {
  593. $on = $child->on;
  594. }
  595. $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
  596. if (!empty($child->where)) {
  597. $this->andWhere($child->where);
  598. }
  599. if (!empty($child->having)) {
  600. $this->andHaving($child->having);
  601. }
  602. if (!empty($child->orderBy)) {
  603. $this->addOrderBy($child->orderBy);
  604. }
  605. if (!empty($child->groupBy)) {
  606. $this->addGroupBy($child->groupBy);
  607. }
  608. if (!empty($child->params)) {
  609. $this->addParams($child->params);
  610. }
  611. if (!empty($child->join)) {
  612. foreach ($child->join as $join) {
  613. $this->join[] = $join;
  614. }
  615. }
  616. if (!empty($child->union)) {
  617. foreach ($child->union as $union) {
  618. $this->union[] = $union;
  619. }
  620. }
  621. }
  622. /**
  623. * Sets the ON condition for a relational query.
  624. * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
  625. * Otherwise, the condition will be used in the WHERE part of a query.
  626. *
  627. * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
  628. *
  629. * ```php
  630. * public function getActiveUsers()
  631. * {
  632. * return $this->hasMany(User::className(), ['id' => 'user_id'])
  633. * ->onCondition(['active' => true]);
  634. * }
  635. * ```
  636. *
  637. * Note that this condition is applied in case of a join as well as when fetching the related records.
  638. * Thus only fields of the related table can be used in the condition. Trying to access fields of the primary
  639. * record will cause an error in a non-join-query.
  640. *
  641. * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
  642. * @param array $params the parameters (name => value) to be bound to the query.
  643. * @return $this the query object itself
  644. */
  645. public function onCondition($condition, $params = [])
  646. {
  647. $this->on = $condition;
  648. $this->addParams($params);
  649. return $this;
  650. }
  651. /**
  652. * Adds an additional ON condition to the existing one.
  653. * The new condition and the existing one will be joined using the 'AND' operator.
  654. * @param string|array $condition the new ON condition. Please refer to [[where()]]
  655. * on how to specify this parameter.
  656. * @param array $params the parameters (name => value) to be bound to the query.
  657. * @return $this the query object itself
  658. * @see onCondition()
  659. * @see orOnCondition()
  660. */
  661. public function andOnCondition($condition, $params = [])
  662. {
  663. if ($this->on === null) {
  664. $this->on = $condition;
  665. } else {
  666. $this->on = ['and', $this->on, $condition];
  667. }
  668. $this->addParams($params);
  669. return $this;
  670. }
  671. /**
  672. * Adds an additional ON condition to the existing one.
  673. * The new condition and the existing one will be joined using the 'OR' operator.
  674. * @param string|array $condition the new ON condition. Please refer to [[where()]]
  675. * on how to specify this parameter.
  676. * @param array $params the parameters (name => value) to be bound to the query.
  677. * @return $this the query object itself
  678. * @see onCondition()
  679. * @see andOnCondition()
  680. */
  681. public function orOnCondition($condition, $params = [])
  682. {
  683. if ($this->on === null) {
  684. $this->on = $condition;
  685. } else {
  686. $this->on = ['or', $this->on, $condition];
  687. }
  688. $this->addParams($params);
  689. return $this;
  690. }
  691. /**
  692. * Specifies the junction table for a relational query.
  693. *
  694. * Use this method to specify a junction table when declaring a relation in the [[ActiveRecord]] class:
  695. *
  696. * ```php
  697. * public function getItems()
  698. * {
  699. * return $this->hasMany(Item::className(), ['id' => 'item_id'])
  700. * ->viaTable('order_item', ['order_id' => 'id']);
  701. * }
  702. * ```
  703. *
  704. * @param string $tableName the name of the junction table.
  705. * @param array $link the link between the junction table and the table associated with [[primaryModel]].
  706. * The keys of the array represent the columns in the junction table, and the values represent the columns
  707. * in the [[primaryModel]] table.
  708. * @param callable $callable a PHP callback for customizing the relation associated with the junction table.
  709. * Its signature should be `function($query)`, where `$query` is the query to be customized.
  710. * @return $this the query object itself
  711. * @throws InvalidConfigException when query is not initialized properly
  712. * @see via()
  713. */
  714. public function viaTable($tableName, $link, callable $callable = null)
  715. {
  716. $modelClass = $this->primaryModel ? get_class($this->primaryModel) : $this->modelClass;
  717. $relation = new self($modelClass, [
  718. 'from' => [$tableName],
  719. 'link' => $link,
  720. 'multiple' => true,
  721. 'asArray' => true,
  722. ]);
  723. $this->via = $relation;
  724. if ($callable !== null) {
  725. call_user_func($callable, $relation);
  726. }
  727. return $this;
  728. }
  729. /**
  730. * Define an alias for the table defined in [[modelClass]].
  731. *
  732. * This method will adjust [[from]] so that an already defined alias will be overwritten.
  733. * If none was defined, [[from]] will be populated with the given alias.
  734. *
  735. * @param string $alias the table alias.
  736. * @return $this the query object itself
  737. * @since 2.0.7
  738. */
  739. public function alias($alias)
  740. {
  741. if (empty($this->from) || count($this->from) < 2) {
  742. list($tableName) = $this->getTableNameAndAlias();
  743. $this->from = [$alias => $tableName];
  744. } else {
  745. $tableName = $this->getPrimaryTableName();
  746. foreach ($this->from as $key => $table) {
  747. if ($table === $tableName) {
  748. unset($this->from[$key]);
  749. $this->from[$alias] = $tableName;
  750. }
  751. }
  752. }
  753. return $this;
  754. }
  755. /**
  756. * {@inheritdoc}
  757. * @since 2.0.12
  758. */
  759. public function getTablesUsedInFrom()
  760. {
  761. if (empty($this->from)) {
  762. return $this->cleanUpTableNames([$this->getPrimaryTableName()]);
  763. }
  764. return parent::getTablesUsedInFrom();
  765. }
  766. /**
  767. * @return string primary table name
  768. * @since 2.0.12
  769. */
  770. protected function getPrimaryTableName()
  771. {
  772. /* @var $modelClass ActiveRecord */
  773. $modelClass = $this->modelClass;
  774. return $modelClass::tableName();
  775. }
  776. }