ActiveQuery.php 30 KB

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