Skip to content

Commit 5ed6391

Browse files
committed
Added IGNORE INDEX
1 parent 8a9e4e9 commit 5ed6391

File tree

1 file changed

+59
-4
lines changed

1 file changed

+59
-4
lines changed

src/ModelUseIndex.php

+59-4
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)