Skip to content Skip to sidebar Skip to footer

Laravel Eloquent - Is There A Way To Add Hint Before Select?

With Laravel 5.7, PostgreSQL and pg_hint_plan, I want to write a SQL query like /*+ IndexScan(users) */ SELECT * FROM users WHERE age=10; with eloquent. SELECT * FROM users WHERE

Solution 1:

You can override the PostgresConnection class and the PostgresGrammar class to add your own logic to the compileSelect method in the PostgresGrammar class.

classPostgresConnectionextends \Illuminate\Database\PostgresConnection{
    /**
     * @return \Illuminate\Database\Grammar|\Illuminate\Database\Query\Grammars\PostgresGrammar
     */protectedfunctiongetDefaultQueryGrammar()
    {
        return$this->withTablePrefix(new PostgresGrammar());
    }
}
classPostgresGrammarextends \Illuminate\Database\Query\Grammars\PostgresGrammar{
    /**
     * Compile a select query into SQL.
     *
     * @param  \Illuminate\Database\Query\Builder $query
     *
     * @return string
     */publicfunctioncompileSelect(Builder $query)
    {
        $sql = parent::compileSelect($query);
        return'/*+ IndexScan(users) */' . $sql;
    }
}

Need to define a service provider class, it is very important to register this service provider before Illuminate\Database\DatabaseServiceProvider::class

classDatabasePostgresServiceProviderextendsServiceProvider{
    /**
     * 此外,在 Illuminate\Database\DatabaseServiceProvider::class 之前注册此服务提供程序非常重要
     *
     * Bootstrap any application services.
     *
     * @return void
     */publicfunctionboot()
    {
        Connection::resolverFor('postgres', function ($connection, $database, $prefix, $config) {
            // Use your own defined PostgresConnection class here.returnnew PostgresConnection($connection, $database, $prefix, $config);
        });
    }
}

Configured in config/app.php

'providers' => [
        // .... 
        DatabasePostgresServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,

    ],

Post a Comment for "Laravel Eloquent - Is There A Way To Add Hint Before Select?"