ActiveQuery.php 25.7 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8
namespace yii\db;
Qiang Xue committed
9

Qiang Xue committed
10 11 12
/**
 * ActiveQuery represents a DB query associated with an Active Record class.
 *
13 14
 * An ActiveQuery can be a normal query or be used in a relational context.
 *
15
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
16 17 18 19
 * Relational queries are created by [[ActiveRecord::hasOne()]] and [[ActiveRecord::hasMany()]].
 *
 * Normal Query
 * ------------
Qiang Xue committed
20 21 22 23 24
 *
 * ActiveQuery mainly provides the following methods to retrieve the query results:
 *
 * - [[one()]]: returns a single record populated with the first row of data.
 * - [[all()]]: returns all records based on the query results.
25 26 27 28 29 30
 * - [[count()]]: returns the number of records.
 * - [[sum()]]: returns the sum over the specified column.
 * - [[average()]]: returns the average over the specified column.
 * - [[min()]]: returns the min over the specified column.
 * - [[max()]]: returns the max over the specified column.
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
31
 * - [[column()]]: returns the value of the first column in the query result.
Qiang Xue committed
32 33 34 35 36 37 38
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
 *
 * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
 * [[orderBy()]] to customize the query options.
 *
 * ActiveQuery also provides the following additional query options:
 *
Qiang Xue committed
39 40 41
 * - [[with()]]: list of relations that this query should be performed with.
 * - [[indexBy()]]: the name of the column by which the query result should be indexed.
 * - [[asArray()]]: whether to return each record as an array.
Qiang Xue committed
42 43 44
 *
 * These options can be configured using methods of the same name. For example:
 *
45
 * ```php
Qiang Xue committed
46
 * $customers = Customer::find()->with('orders')->asArray()->all();
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
 * ```
 *
 * Relational query
 * ----------------
 *
 * In relational context ActiveQuery represents a relation between two Active Record classes.
 *
 * Relational ActiveQuery instances are usually created by calling [[ActiveRecord::hasOne()]] and
 * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
 * a getter method which calls one of the above methods and returns the created ActiveQuery object.
 *
 * A relation is specified by [[link]] which represents the association between columns
 * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
 *
 * If a relation involves a pivot table, it may be specified by [[via()]] or [[viaTable()]] method.
 * These methods may only be called in a relational context. Same is true for [[inverseOf()]], which
 * marks a relation as inverse of another relation and [[onCondition()]] which adds a condition that
Qiang Xue committed
64
 * is to be added to relational query join condition.
Qiang Xue committed
65 66
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
67
 * @author Carsten Brandt <mail@cebe.cc>
Qiang Xue committed
68 69
 * @since 2.0
 */
70
class ActiveQuery extends Query implements ActiveQueryInterface
Qiang Xue committed
71
{
72 73 74
    use ActiveQueryTrait;
    use ActiveRelationTrait;

75 76 77 78 79
    /**
     * @event Event an event that is triggered when the query is initialized via [[init()]].
     */
    const EVENT_INIT = 'init';

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    /**
     * @var string the SQL statement to be executed for retrieving AR records.
     * This is set by [[ActiveRecord::findBySql()]].
     */
    public $sql;
    /**
     * @var string|array the join condition to be used when this query is used in a relational context.
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
     * Otherwise, the condition will be used in the WHERE part of a query.
     * Please refer to [[Query::where()]] on how to specify this parameter.
     * @see onCondition()
     */
    public $on;
    /**
     * @var array a list of relations that this query should be joined with
     */
    public $joinWith;

98

Qiang Xue committed
99 100 101 102 103 104 105 106 107 108 109
    /**
     * Constructor.
     * @param array $modelClass the model class associated with this query
     * @param array $config configurations to be applied to the newly created query object
     */
    public function __construct($modelClass, $config = [])
    {
        $this->modelClass = $modelClass;
        parent::__construct($config);
    }

110 111 112 113 114 115 116 117 118 119 120 121
    /**
     * Initializes the object.
     * This method is called at the end of the constructor. The default implementation will trigger
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
     * to ensure triggering of the event.
     */
    public function init()
    {
        parent::init();
        $this->trigger(self::EVENT_INIT);
    }

122 123
    /**
     * Executes query and returns all results as an array.
124 125
     * @param Connection $db the DB connection used to create the DB command.
     * If null, the DB connection returned by [[modelClass]] will be used.
126 127 128 129 130 131 132
     * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

Qiang Xue committed
133 134 135 136 137 138 139 140 141 142 143
    /**
     * @inheritdoc
     */
    public function prepareBuild($builder)
    {
        if (!empty($this->joinWith)) {
            $this->buildJoinWith();
            $this->joinWith = null;    // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
        }

        if (empty($this->from)) {
144
            /* @var $modelClass ActiveRecord */
Qiang Xue committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
            $modelClass = $this->modelClass;
            $tableName = $modelClass::tableName();
            $this->from = [$tableName];
        }

        if (empty($this->select) && !empty($this->join)) {
            foreach ((array)$this->from as $alias => $table) {
                if (is_string($alias)) {
                    $this->select = ["$alias.*"];
                } elseif (is_string($table)) {
                    if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $table, $matches)) {
                        $alias = $matches[2];
                    } else {
                        $alias = $table;
                    }
                    $this->select = ["$alias.*"];
                }
                break;
            }
        }
    }

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    /**
     * @inheritdoc
     */
    public function prepareResult($rows)
    {
        if (empty($rows)) {
            return [];
        }

        $models = $this->createModels($rows);
        if (!empty($this->join) && $this->indexBy === null) {
            $models = $this->removeDuplicatedModels($models);
        }
        if (!empty($this->with)) {
            $this->findWith($this->with, $models);
        }
        if (!$this->asArray) {
            foreach ($models as $model) {
                $model->afterFind();
            }
        }

        return $models;
    }

    /**
     * Removes duplicated models by checking their primary key values.
     * This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
195
     * @param array $models the models to be checked
196 197 198 199 200
     * @return array the distinctive models
     */
    private function removeDuplicatedModels($models)
    {
        $hash = [];
201
        /* @var $class ActiveRecord */
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        $class = $this->modelClass;
        $pks = $class::primaryKey();

        if (count($pks) > 1) {
            foreach ($models as $i => $model) {
                $key = [];
                foreach ($pks as $pk) {
                    $key[] = $model[$pk];
                }
                $key = serialize($key);
                if (isset($hash[$key])) {
                    unset($models[$i]);
                } else {
                    $hash[$key] = true;
                }
            }
        } else {
            $pk = reset($pks);
            foreach ($models as $i => $model) {
                $key = $model[$pk];
                if (isset($hash[$key])) {
                    unset($models[$i]);
224
                } elseif ($key !== null) {
225 226 227 228 229 230 231 232 233 234
                    $hash[$key] = true;
                }
            }
        }

        return array_values($models);
    }

    /**
     * Executes query and returns a single row of result.
235 236
     * @param Connection $db the DB connection used to create the DB command.
     * If null, the DB connection returned by [[modelClass]] will be used.
237
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
238 239
     * the query result may be either an array or an ActiveRecord object. Null will be returned
     * if the query results in nothing.
240 241 242
     */
    public function one($db = null)
    {
243
        $row = parent::one($db);
244
        if ($row !== false) {
245 246
            $models = $this->prepareResult([$row]);
            return reset($models) ?: null;
247 248 249 250 251 252 253
        } else {
            return null;
        }
    }

    /**
     * Creates a DB command that can be used to execute this query.
254 255 256
     * @param Connection $db the DB connection used to create the DB command.
     * If null, the DB connection returned by [[modelClass]] will be used.
     * @return Command the created DB command instance.
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
     */
    public function createCommand($db = null)
    {
        if ($this->primaryModel === null) {
            // not a relational context or eager loading
            if (!empty($this->on)) {
                $where = $this->where;
                $this->andWhere($this->on);
                $command = $this->createCommandInternal($db);
                $this->where = $where;

                return $command;
            } else {
                return $this->createCommandInternal($db);
            }
        } else {
            // lazy loading of a relation
            return $this->createRelationalCommand($db);
        }
    }

    /**
     * Creates a DB command that can be used to execute this query.
Carsten Brandt committed
280
     * @param Connection|null $db the DB connection used to create the DB command.
281 282
     * If null, the DB connection returned by [[modelClass]] will be used.
     * @return Command the created DB command instance.
283 284 285
     */
    protected function createCommandInternal($db)
    {
286
        /* @var $modelClass ActiveRecord */
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        $modelClass = $this->modelClass;
        if ($db === null) {
            $db = $modelClass::getDb();
        }

        if ($this->sql === null) {
            list ($sql, $params) = $db->getQueryBuilder()->build($this);
        } else {
            $sql = $this->sql;
            $params = $this->params;
        }

        return $db->createCommand($sql, $params);
    }

    /**
     * Creates a command for lazy loading of a relation.
Carsten Brandt committed
304
     * @param Connection|null $db the DB connection used to create the DB command.
305
     * @return Command the created DB command instance.
306 307 308 309 310 311 312 313 314 315 316
     */
    private function createRelationalCommand($db = null)
    {
        $where = $this->where;

        if ($this->via instanceof self) {
            // via pivot table
            $viaModels = $this->via->findPivotRows([$this->primaryModel]);
            $this->filterByModels($viaModels);
        } elseif (is_array($this->via)) {
            // via relation
317
            /* @var $viaQuery ActiveQuery */
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
            list($viaName, $viaQuery) = $this->via;
            if ($viaQuery->multiple) {
                $viaModels = $viaQuery->all();
                $this->primaryModel->populateRelation($viaName, $viaModels);
            } else {
                $model = $viaQuery->one();
                $this->primaryModel->populateRelation($viaName, $model);
                $viaModels = $model === null ? [] : [$model];
            }
            $this->filterByModels($viaModels);
        } else {
            $this->filterByModels([$this->primaryModel]);
        }

        if (!empty($this->on)) {
            $this->andWhere($this->on);
        }

        $command = $this->createCommandInternal($db);

        $this->where = $where;

        return $command;
    }

    /**
     * Joins with the specified relations.
     *
     * This method allows you to reuse existing relation definitions to perform JOIN queries.
     * Based on the definition of the specified relation(s), the method will append one or multiple
     * JOIN statements to the current query.
     *
     * If the `$eagerLoading` parameter is true, the method will also eager loading the specified relations,
     * which is equivalent to calling [[with()]] using the specified relations.
     *
     * Note that because a JOIN query will be performed, you are responsible to disambiguate column names.
     *
     * This method differs from [[with()]] in that it will build up and execute a JOIN SQL statement
     * for the primary table. And when `$eagerLoading` is true, it will call [[with()]] in addition with the specified relations.
     *
     * @param array $with the relations to be joined. Each array element represents a single relation.
359 360 361 362
     * The array keys are relation names, and the array values are the corresponding anonymous functions that
     * can be used to modify the relation queries on-the-fly. If a relation query does not need modification,
     * you may use the relation name as the array value. Sub-relations can also be specified (see [[with()]]).
     * For example,
363 364 365 366 367 368 369
     *
     * ```php
     * // find all orders that contain books, and eager loading "books"
     * Order::find()->joinWith('books', true, 'INNER JOIN')->all();
     * // find all orders, eager loading "books", and sort the orders and books by the book names.
     * Order::find()->joinWith([
     *     'books' => function ($query) {
370
     *         $query->orderBy('item.name');
371 372 373 374
     *     }
     * ])->all();
     * ```
     *
375 376 377 378 379 380 381
     * @param boolean|array $eagerLoading whether to eager load the relations specified in `$with`.
     * When this is a boolean, it applies to all relations specified in `$with`. Use an array
     * to explicitly list which relations in `$with` need to be eagerly loaded.
     * @param string|array $joinType the join type of the relations specified in `$with`.
     * When this is a string, it applies to all relations specified in `$with`. Use an array
     * in the format of `relationName => joinType` to specify different join types for different relations.
     * @return static the query object itself
382 383 384 385 386 387 388 389 390 391
     */
    public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
    {
        $this->joinWith[] = [(array) $with, $eagerLoading, $joinType];

        return $this;
    }

    private function buildJoinWith()
    {
Qiang Xue committed
392 393 394
        $join = $this->join;
        $this->join = [];

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
        foreach ($this->joinWith as $config) {
            list ($with, $eagerLoading, $joinType) = $config;
            $this->joinWithRelations(new $this->modelClass, $with, $joinType);

            if (is_array($eagerLoading)) {
                foreach ($with as $name => $callback) {
                    if (is_integer($name)) {
                        if (!in_array($callback, $eagerLoading, true)) {
                            unset($with[$name]);
                        }
                    } elseif (!in_array($name, $eagerLoading, true)) {
                        unset($with[$name]);
                    }
                }
            } elseif (!$eagerLoading) {
                $with = [];
            }

            $this->with($with);
        }
Qiang Xue committed
415

416 417 418
        // remove duplicated joins added by joinWithRelations that may be added
        // e.g. when joining a relation and a via relation at the same time
        $uniqueJoins = [];
Thiago Talma committed
419
        foreach ($this->join as $j) {
420 421 422 423
            $uniqueJoins[serialize($j)] = $j;
        }
        $this->join = array_values($uniqueJoins);

Qiang Xue committed
424 425 426 427 428
        if (!empty($join)) {
            // append explicit join to joinWith()
            // https://github.com/yiisoft/yii2/issues/2880
            $this->join = empty($this->join) ? $join : array_merge($this->join, $join);
        }
429 430 431 432 433 434
    }

    /**
     * Inner joins with the specified relations.
     * This is a shortcut method to [[joinWith()]] with the join type set as "INNER JOIN".
     * Please refer to [[joinWith()]] for detailed usage of this method.
435 436 437
     * @param array $with the relations to be joined with
     * @param boolean|array $eagerLoading whether to eager loading the relations
     * @return static the query object itself
438 439 440 441 442 443 444 445 446
     * @see joinWith()
     */
    public function innerJoinWith($with, $eagerLoading = true)
    {
        return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
    }

    /**
     * Modifies the current query by adding join fragments based on the given relations.
447 448
     * @param ActiveRecord $model the primary model
     * @param array $with the relations to be joined
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
     * @param string|array $joinType the join type
     */
    private function joinWithRelations($model, $with, $joinType)
    {
        $relations = [];

        foreach ($with as $name => $callback) {
            if (is_integer($name)) {
                $name = $callback;
                $callback = null;
            }

            $primaryModel = $model;
            $parent = $this;
            $prefix = '';
            while (($pos = strpos($name, '.')) !== false) {
                $childName = substr($name, $pos + 1);
                $name = substr($name, 0, $pos);
                $fullName = $prefix === '' ? $name : "$prefix.$name";
                if (!isset($relations[$fullName])) {
                    $relations[$fullName] = $relation = $primaryModel->getRelation($name);
                    $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
                } else {
                    $relation = $relations[$fullName];
                }
                $primaryModel = new $relation->modelClass;
                $parent = $relation;
                $prefix = $fullName;
                $name = $childName;
            }

            $fullName = $prefix === '' ? $name : "$prefix.$name";
            if (!isset($relations[$fullName])) {
                $relations[$fullName] = $relation = $primaryModel->getRelation($name);
                if ($callback !== null) {
                    call_user_func($callback, $relation);
                }
                $this->joinWithRelation($parent, $relation, $this->getJoinType($joinType, $fullName));
            }
        }
    }

    /**
     * Returns the join type based on the given join type parameter and the relation name.
493 494 495
     * @param string|array $joinType the given join type(s)
     * @param string $name relation name
     * @return string the real join type
496 497 498 499 500 501 502 503 504 505 506 507
     */
    private function getJoinType($joinType, $name)
    {
        if (is_array($joinType) && isset($joinType[$name])) {
            return $joinType[$name];
        } else {
            return is_string($joinType) ? $joinType : 'INNER JOIN';
        }
    }

    /**
     * Returns the table name and the table alias for [[modelClass]].
508 509
     * @param ActiveQuery $query
     * @return array the table name and the table alias.
510 511 512 513
     */
    private function getQueryTableName($query)
    {
        if (empty($query->from)) {
514
            /* @var $modelClass ActiveRecord */
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
            $modelClass = $query->modelClass;
            $tableName = $modelClass::tableName();
        } else {
            $tableName = '';
            foreach ($query->from as $alias => $tableName) {
                if (is_string($alias)) {
                    return [$tableName, $alias];
                } else {
                    break;
                }
            }
        }

        if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
            $alias = $matches[2];
        } else {
            $alias = $tableName;
        }

        return [$tableName, $alias];
    }

    /**
     * Joins a parent query with a child query.
     * The current query object will be modified accordingly.
     * @param ActiveQuery $parent
     * @param ActiveQuery $child
542
     * @param string $joinType
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
     */
    private function joinWithRelation($parent, $child, $joinType)
    {
        $via = $child->via;
        $child->via = null;
        if ($via instanceof ActiveQuery) {
            // via table
            $this->joinWithRelation($parent, $via, $joinType);
            $this->joinWithRelation($via, $child, $joinType);

            return;
        } elseif (is_array($via)) {
            // via relation
            $this->joinWithRelation($parent, $via[1], $joinType);
            $this->joinWithRelation($via[1], $child, $joinType);

            return;
        }

        list ($parentTable, $parentAlias) = $this->getQueryTableName($parent);
        list ($childTable, $childAlias) = $this->getQueryTableName($child);

        if (!empty($child->link)) {

            if (strpos($parentAlias, '{{') === false) {
                $parentAlias = '{{' . $parentAlias . '}}';
            }
            if (strpos($childAlias, '{{') === false) {
                $childAlias = '{{' . $childAlias . '}}';
            }

            $on = [];
            foreach ($child->link as $childColumn => $parentColumn) {
                $on[] = "$parentAlias.[[$parentColumn]] = $childAlias.[[$childColumn]]";
            }
            $on = implode(' AND ', $on);
            if (!empty($child->on)) {
                $on = ['and', $on, $child->on];
            }
        } else {
            $on = $child->on;
        }
585
        $this->join($joinType, empty($child->from) ? $childTable : $child->from, $on);
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627

        if (!empty($child->where)) {
            $this->andWhere($child->where);
        }
        if (!empty($child->having)) {
            $this->andHaving($child->having);
        }
        if (!empty($child->orderBy)) {
            $this->addOrderBy($child->orderBy);
        }
        if (!empty($child->groupBy)) {
            $this->addGroupBy($child->groupBy);
        }
        if (!empty($child->params)) {
            $this->addParams($child->params);
        }
        if (!empty($child->join)) {
            foreach ($child->join as $join) {
                $this->join[] = $join;
            }
        }
        if (!empty($child->union)) {
            foreach ($child->union as $union) {
                $this->union[] = $union;
            }
        }
    }

    /**
     * Sets the ON condition for a relational query.
     * The condition will be used in the ON part when [[ActiveQuery::joinWith()]] is called.
     * Otherwise, the condition will be used in the WHERE part of a query.
     *
     * Use this method to specify additional conditions when declaring a relation in the [[ActiveRecord]] class:
     *
     * ```php
     * public function getActiveUsers()
     * {
     *     return $this->hasMany(User::className(), ['id' => 'user_id'])->onCondition(['active' => true]);
     * }
     * ```
     *
628 629 630
     * @param string|array $condition the ON condition. Please refer to [[Query::where()]] on how to specify this parameter.
     * @param array $params the parameters (name => value) to be bound to the query.
     * @return static the query object itself
631 632 633 634 635
     */
    public function onCondition($condition, $params = [])
    {
        $this->on = $condition;
        $this->addParams($params);
636 637
        return $this;
    }
638

639 640 641 642 643
    /**
     * Adds an additional ON condition to the existing one.
     * The new condition and the existing one will be joined using the 'AND' operator.
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
     * on how to specify this parameter.
Thiago Talma committed
644
     * @param array $params the parameters (name => value) to be bound to the query.
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
     * @return static the query object itself
     * @see onCondition()
     * @see orOnCondition()
     */
    public function andOnCondition($condition, $params = [])
    {
        if ($this->on === null) {
            $this->on = $condition;
        } else {
            $this->on = ['and', $this->on, $condition];
        }
        $this->addParams($params);
        return $this;
    }

    /**
     * Adds an additional ON condition to the existing one.
     * The new condition and the existing one will be joined using the 'OR' operator.
     * @param string|array $condition the new ON condition. Please refer to [[where()]]
     * on how to specify this parameter.
Thiago Talma committed
665
     * @param array $params the parameters (name => value) to be bound to the query.
666 667 668 669 670 671 672 673 674 675 676 677
     * @return static the query object itself
     * @see onCondition()
     * @see andOnCondition()
     */
    public function orOnCondition($condition, $params = [])
    {
        if ($this->on === null) {
            $this->on = $condition;
        } else {
            $this->on = ['or', $this->on, $condition];
        }
        $this->addParams($params);
678 679 680 681 682 683 684 685 686 687 688 689
        return $this;
    }

    /**
     * Specifies the pivot table for a relational query.
     *
     * Use this method to specify a pivot table when declaring a relation in the [[ActiveRecord]] class:
     *
     * ```php
     * public function getItems()
     * {
     *     return $this->hasMany(Item::className(), ['id' => 'item_id'])
690
     *                 ->viaTable('order_item', ['order_id' => 'id']);
691 692 693
     * }
     * ```
     *
694 695 696 697 698 699
     * @param string $tableName the name of the pivot table.
     * @param array $link the link between the pivot table and the table associated with [[primaryModel]].
     * The keys of the array represent the columns in the pivot table, and the values represent the columns
     * in the [[primaryModel]] table.
     * @param callable $callable a PHP callback for customizing the relation associated with the pivot table.
     * Its signature should be `function($query)`, where `$query` is the query to be customized.
700 701 702
     * @return static
     * @see via()
     */
703
    public function viaTable($tableName, $link, callable $callable = null)
704
    {
Qiang Xue committed
705
        $relation = new ActiveQuery(get_class($this->primaryModel), [
706 707 708 709 710 711 712 713 714 715 716 717
            'from' => [$tableName],
            'link' => $link,
            'multiple' => true,
            'asArray' => true,
        ]);
        $this->via = $relation;
        if ($callable !== null) {
            call_user_func($callable, $relation);
        }

        return $this;
    }
Qiang Xue committed
718
}