laravel 如何在 eloquent 中使用力指数

hel*_*owd 6 php laravel

我真的在laravel雄辩语法麻烦,当我想建立一个SQL这样的:

select * from order force index(type) where type=1

无论如何,我可以使用 DB 来构建它,例如:

DB::table(DB::raw('order force index(type)'))->where('type', 1)->get();

但是无论如何可以使用 eloquent 来做到这一点,例如:Order::forceIndex('type')..

谢谢

mik*_*n32 8

您可以通过创建一个本地范围来实现此目的,该范围在应用时更改构建器的表名称。在使用表之前应检查该表的索引。如果提供了无效的索引名称,您可以抛出异常或忽略它(我选择了后一种方法。)

<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/*
 * Class Order
 *
 * @method \Illuminate\Database\Eloquent\Builder useIndex(string $index)
 * @method \Illuminate\Database\Eloquent\Builder forceIndex(string $index)
 */
class Order extends Model
{
    private function tableIndexExists(string $index): boolean
    {
        $table = $this->getTable();
        $index = strtolower($index);
        $indices = Schema::getConnection()
            ->getDoctrineSchemaManager()
            ->listTableIndexes($table);

        return array_key_exists($index, $indices);
    }

    public function scopeUseIndex(Builder $query, string $index): Builder
    {
        $table = $this->getTable();

        return $this->tableIndexExists($index)
            ? $query->from(DB::raw("`$table` USE INDEX(`$index`)"))
            : $query;
    }

    public function scopeForceIndex(Builder $query, string $index): Builder
    {
        $table = $this->getTable();

        return $this->tableIndexExists($index)
            ? $query->from(DB::raw("`$table` FORCE INDEX(`$index`)"))
            : $query;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要在多个模型上执行此操作,可以轻松将其添加到特征中并导入。文档块确保您的 IDE 知道代码完成的神奇方法。

然后你可以像这样使用它:

$orders = Order::forceIndex("orders_type_index")->where("type", 1)->get();

// or this:
$orders = Customer::find(234)
    ->orders()
    ->forceIndex("orders_type_index")
    ->where("type", 1)
    ->get();
Run Code Online (Sandbox Code Playgroud)