PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Laravel eloquente - Existe uma maneira de adicionar Hint antes de SELECT?


Você pode substituir a classe PostgresConnection e a classe PostgresGrammar para adicionar sua própria lógica ao método compileSelect na classe PostgresGrammar.
class PostgresConnection extends \Illuminate\Database\PostgresConnection
{
    /**
     * @return \Illuminate\Database\Grammar|\Illuminate\Database\Query\Grammars\PostgresGrammar
     */
    protected function getDefaultQueryGrammar()
    {
        return $this->withTablePrefix(new PostgresGrammar());
    }
}
class PostgresGrammar extends \Illuminate\Database\Query\Grammars\PostgresGrammar
{
    /**
     * Compile a select query into SQL.
     *
     * @param  \Illuminate\Database\Query\Builder $query
     *
     * @return string
     */
    public function compileSelect(Builder $query)
    {
        $sql = parent::compileSelect($query);
        return '/*+ IndexScan(users) */' . $sql;
    }
}

Precisa definir uma classe de provedor de serviço, é muito importante registrar este provedor de serviço antes de Illuminate\Database\DatabaseServiceProvider::class
class DatabasePostgresServiceProvider extends ServiceProvider
{
    /**
     * 此外,在 Illuminate\Database\DatabaseServiceProvider::class 之前注册此服务提供程序非常重要
     *
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Connection::resolverFor('postgres', function ($connection, $database, $prefix, $config) {
            // Use your own defined PostgresConnection class here.
            return new PostgresConnection($connection, $database, $prefix, $config);
        });
    }
}


Configurado em config/app.php
'providers' => [
        // .... 
        DatabasePostgresServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,

    ],