Created
May 15, 2012 19:27
-
-
Save arnaud-lb/2704404 to your computer and use it in GitHub Desktop.
USE INDEX / FORCE INDEX in a Doctrine2 DQL query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Another composer package: shipmonk/doctrine-mysql-index-hints
- works even for tables nor present in DQL, but present in SQL (Single Table Inheritance)
- supports Doctrine ORM 3
- supports subselects
Thanks for the solution ! 🙏
Small fix : in example.php line 8, you can use UseIndexWalker::class
instead of 'UseIndexWalker'
. It avoids having hardcoded strings in code + it manages if the file is in a different namespace. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@renatogcarvalho Thank you for noticing! I added your fix. 👍 Best regards, Gergő