When you want to use or force index with Query Builder in Laravel, you can do it
$query = SomeModel::query()->getModel()
$query->setTable(DB::raw($query->getTable() . ' USE INDEX(index_name)'))
$results = $query->get();
In complex queries with with() previous solution doesn't work. Better to overwrite base query 'from' value instead:
$query = SomeModel::with('some_relations')...->orderBy();
$query->getQuery()->from(DB::raw($query->getQuery()->from . ' USE INDEX (index_name)'));
// or just
$query->getQuery()->from(DB::raw('`table` USE INDEX (index_name)'));
$results = $query->get();
Hope it will helpful with you.
Top comments (2)
Is it not possible with Eloquent?
no, it's possiable