Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
USE INDEX / FORCE INDEX in a Doctrine2 DQL query (with support for multiple tables in the FROM clause).
use UseIndexWalker;
use Doctrine\ORM\Query
$query = $em->createQuery("SELECT f FROM Foo f WHERE f.a = 1 and f.b = 2");
$query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'UseIndexWalker');
$query->setHint(UseIndexWalker::HINT_USE_INDEX, 'some_index_name');
use Doctrine\ORM\Query\SqlWalker;
class UseIndexWalker extends SqlWalker
const HINT_USE_INDEX = 'UseIndexWalker.UseIndex';
public function walkFromClause($fromClause)
$sql = parent::walkFromClause($fromClause);
$index = $this->getQuery()->getHint(self::HINT_USE_INDEX);
return preg_replace('/( INNER JOIN| LEFT JOIN|$)/', sprintf(' USE INDEX(%s)\1', $index), $sql, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.