Skip to content

Commit 4d9788f

Browse files
committed
Added IGNORE INDEX
1 parent 8a9e4e9 commit 4d9788f

File tree

2 files changed

+62
-4
lines changed

2 files changed

+62
-4
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ Tells MySQL to use an index if it possible.
4343
#### `forceIndex($indexName)`
4444
Force MySQL to use an index if it possible.
4545

46+
#### `ignoreIndex($indexName)`
47+
Ask MySQL to ignore an index if it possible.
48+
4649
## Security
4750

4851
If you discover any security related issues, please use the issue tracker.

src/ModelUseIndex.php

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,74 @@
99
/**
1010
* @method Builder useIndex(string $index)
1111
* @method Builder forceIndex(string $index)
12+
* @method Builder ignoreIndex(string $index)
1213
*
1314
*/
1415
trait ModelUseIndex
1516
{
16-
public function scopeUseIndex($query, string $index): Builder
17+
private $from = [];
18+
19+
/**
20+
* @param string|array $index
21+
* @return string
22+
*/
23+
private function parseIndexName($index): string
24+
{
25+
if (is_array($index)) {
26+
return "`" . implode("`, `", $index) . "`";
27+
}else{
28+
return "`" . $index . "`";
29+
}
30+
}
31+
32+
/**
33+
* @param $query
34+
* @param string|array $index
35+
* @return Builder
36+
*/
37+
public function scopeUseIndex($query, $index): Builder
1738
{
1839
$table = $this->getTable();
19-
return $query->from(DB::raw("`$table` USE INDEX(`$index`)"));
40+
$index = $this->parseIndexName($index);
41+
42+
$this->from[] = "USE INDEX($index)";
43+
44+
$raw = "`$table` " . implode(" ", $this->from);
45+
46+
return $query->from(DB::raw($raw));
2047
}
2148

22-
public function scopeForceIndex($query, string $index): Builder
49+
/**
50+
* @param $query
51+
* @param string|array $index
52+
* @return Builder
53+
*/
54+
public function scopeForceIndex($query, $index): Builder
2355
{
2456
$table = $this->getTable();
25-
return $query->from(DB::raw("`$table` FORCE INDEX(`$index`)"));
57+
$index = $this->parseIndexName($index);
58+
59+
$this->from[] = "FORCE INDEX($index)";
60+
61+
$raw = "`$table` " . implode(" ", $this->from);
62+
63+
return $query->from(DB::raw($raw));
64+
}
65+
66+
/**
67+
* @param $query
68+
* @param string|array $index
69+
* @return Builder
70+
*/
71+
public function scopeIgnoreIndex($query, $index): Builder
72+
{
73+
$table = $this->getTable();
74+
$index = $this->parseIndexName($index);
75+
76+
$this->from[] = "IGNORE INDEX($index)";
77+
78+
$raw = "`$table` " . implode(" ", $this->from);
79+
80+
return $query->from(DB::raw($raw));
2681
}
2782
}

0 commit comments

Comments
 (0)