Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ActiveQuery.php 25KB

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