Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
USE INDEX / FORCE INDEX in a Doctrine2 DQL query
<?php
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');
$query->getResult();
<?php
use Doctrine\ORM\Query\SqlWalker;
/**
* Quick hack to allow adding a USE INDEX on the query
*/
class UseIndexWalker extends SqlWalker
{
const HINT_USE_INDEX = 'UseIndexWalker.UseIndex';
public function walkFromClause($fromClause)
{
$result = parent::walkFromClause($fromClause);
if ($index = $this->getQuery()->getHint(self::HINT_USE_INDEX)) {
$result = preg_replace('#(\bFROM\s*\w+\s*\w+)#', '\1 USE INDEX (' . $index . ')', $result);
}
return $result;
}
}
@NakedFerret

This comment has been minimized.

Copy link

commented Feb 21, 2017

Cheers!

@multifinger

This comment has been minimized.

Copy link

commented Apr 11, 2017

Here is modified version of walker,
contains FIX for join-queries

http://stackoverflow.com/questions/16729011/index-hinting-in-doctrine2

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.