diff --git a/framework/db/Query.php b/framework/db/Query.php index 1819c9c3107..a33c3668684 100644 --- a/framework/db/Query.php +++ b/framework/db/Query.php @@ -74,6 +74,12 @@ class Query extends Component implements QueryInterface, ExpressionInterface * @see from() */ public $from; + /** + * @var string|null force to use specific index. For example, `'userTimeCreated'`. + * This is used to construct the FROM clause in a SQL statement. + * @see forceIndex() + */ + public $forceIndex; /** * @var array|null how to group the query results. For example, `['company', 'department']`. * This is used to construct the GROUP BY clause in a SQL statement. @@ -825,6 +831,25 @@ public function from($tables) return $this; } + /** + * Sets the FORCE INDEX part of the query. + * @param string $forceIndex + * + * Here are some examples: + * + * ```php + * // SELECT * FROM `user` FORCE INDEX (userTimeCreated); + * $query = (new \yii\db\Query)->from('user')->forceIndex('userTimeCreated'); + * ``` + * + * @return $this the query object itself + */ + public function forceIndex($forceIndex) + { + $this->forceIndex = $forceIndex; + return $this; + } + /** * Sets the WHERE part of the query. * @@ -1381,6 +1406,7 @@ public static function create($from) 'selectOption' => $from->selectOption, 'distinct' => $from->distinct, 'from' => $from->from, + 'forceIndex' => $from->forceIndex, 'groupBy' => $from->groupBy, 'join' => $from->join, 'having' => $from->having, diff --git a/framework/db/QueryBuilder.php b/framework/db/QueryBuilder.php index 9d243abe122..37dde973615 100644 --- a/framework/db/QueryBuilder.php +++ b/framework/db/QueryBuilder.php @@ -230,7 +230,7 @@ public function build($query, $params = []) $clauses = [ $this->buildSelect($query->select, $params, $query->distinct, $query->selectOption), - $this->buildFrom($query->from, $params), + $this->buildFrom($query->from, $params, $query->forceIndex), $this->buildJoin($query->join, $params), $this->buildWhere($query->where, $params), $this->buildGroupBy($query->groupBy), @@ -1272,9 +1272,10 @@ public function buildSelect($columns, &$params, $distinct = false, $selectOption /** * @param array $tables * @param array $params the binding parameters to be populated + * @param string $forceIndex * @return string the FROM clause built from [[Query::$from]]. */ - public function buildFrom($tables, &$params) + public function buildFrom($tables, &$params, $forceIndex = null) { if (empty($tables)) { return ''; @@ -1282,7 +1283,13 @@ public function buildFrom($tables, &$params) $tables = $this->quoteTableNames($tables, $params); - return 'FROM ' . implode(', ', $tables); + $from = 'FROM ' . implode(', ', $tables); + + if (!empty($forceIndex)) { + $from .= " FORCE INDEX ({$forceIndex}) "; + } + + return $from; } /**