|
9 | 9 | /**
|
10 | 10 | * @method Builder useIndex(string $index)
|
11 | 11 | * @method Builder forceIndex(string $index)
|
| 12 | + * @method Builder ignoreIndex(string $index) |
12 | 13 | *
|
13 | 14 | */
|
14 | 15 | trait ModelUseIndex
|
15 | 16 | {
|
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 |
17 | 38 | {
|
18 | 39 | $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)); |
20 | 47 | }
|
21 | 48 |
|
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 |
23 | 55 | {
|
24 | 56 | $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)); |
26 | 81 | }
|
27 | 82 | }
|
0 commit comments