ActiveQuery.php 32 KB

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