[英]Add custom function to Laravel query builder
I am trying to add USE INDEX()
to the query builder in Laravel.我正在尝试将
USE INDEX()
添加到 Laravel 中的查询生成器中。 I tried to follow similar steps to link and was kind of successful but I cannot manage the last bit and I am not sure my ad-hoc code has created a huge backdoor.我尝试按照类似的步骤进行链接并且有点成功,但我无法管理最后一点,我不确定我的临时代码是否创建了一个巨大的后门。
The target: The target of my exercise is to add Index to the query builder like below:目标:我练习的目标是将索引添加到查询构建器,如下所示:
DB::table('users')->where('id',1)->**useIndex**('users')->get()->first();
Here an option useIndex
specifies the index that I am going to use for this query.这里有一个选项
useIndex
指定了我要用于这个查询的索引。
What I have done yet: Created a class named Connection
in App/Override
我已经做了什么:在
App/Override
中创建了一个名为Connection
的 class
<?php
namespace App\Override;
class Connection extends \Illuminate\Database\MySqlConnection {
//@Override
public function query() {
return new QueryBuilder(
$this,
$this->getQueryGrammar(),
$this->getPostProcessor()
);
}
}
Created a service provider named CustomDatabaseServiceProvider
in App/Providers.在 App/Providers 中创建了一个名为
CustomDatabaseServiceProvider
的服务提供者。 Here I just manipulated registerConnectionServices
function.这里我只是操作了
registerConnectionServices
function。 I further commented Illuminate\Database\DatabaseServiceProvider::class,
and added App\Providers\CustomDatabaseServiceProvider::class,
to app.php
in config directory.我进一步评论了
Illuminate\Database\DatabaseServiceProvider::class,
并将App\Providers\CustomDatabaseServiceProvider::class,
添加到app.php
目录中。
<?php
namespace App\Providers;
use App\Override\Connection;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Query\Grammars\Grammar;
use Illuminate\Database\Schema;
use Illuminate\Contracts\Queue\EntityResolver;
use Illuminate\Database\Connectors\ConnectionFactory;
use Illuminate\Database\Eloquent\Factory as EloquentFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\QueueEntityResolver;
use Illuminate\Support\ServiceProvider;
class CustomDatabaseServiceProvider extends ServiceProvider
{
/**
* The array of resolved Faker instances.
*
* @var array
*/
protected static $fakers = [];
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
Model::setConnectionResolver($this->app['db']);
Model::setEventDispatcher($this->app['events']);
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
Model::clearBootedModels();
$this->registerConnectionServices();
$this->registerEloquentFactory();
$this->registerQueueableEntityResolver();
}
/**
* Register the primary database bindings.
*
* @return void
*/
protected function registerConnectionServices()
{
// The connection factory is used to create the actual connection instances on
// the database. We will inject the factory into the manager so that it may
// make the connections while they are actually needed and not of before.
$this->app->singleton('db.factory', function ($app) {
return new ConnectionFactory($app);
});
// The database manager is used to resolve various connections, since multiple
// connections might be managed. It also implements the connection resolver
// interface which may be used by other components requiring connections.
$this->app->singleton('db', function ($app) {
$dbm = new DatabaseManager($app, $app['db.factory']);
//Extend to include the custom connection (MySql in this example)
$dbm->extend('mysql', function ($config, $name) use ($app) {
//Create default connection from factory
$connection = $app['db.factory']->make($config, $name);
//Instantiate our connection with the default connection data
$new_connection = new Connection(
$connection->getPdo(),
$connection->getDatabaseName(),
$connection->getTablePrefix(),
$config
);
//Set the appropriate grammar object
// $new_connection->setQueryGrammar(new Grammar());
// $new_connection->setSchemaGrammar(new Schema\());
return $new_connection;
});
return $dbm;
});
$this->app->bind('db.connection', function ($app) {
return $app['db']->connection();
});
}
/**
* Register the Eloquent factory instance in the container.
*
* @return void
*/
protected function registerEloquentFactory()
{
$this->app->singleton(FakerGenerator::class, function ($app, $parameters) {
$locale = $parameters['locale'] ?? $app['config']->get('app.faker_locale', 'en_US');
if (!isset(static::$fakers[$locale])) {
static::$fakers[$locale] = FakerFactory::create($locale);
}
static::$fakers[$locale]->unique(true);
return static::$fakers[$locale];
});
$this->app->singleton(EloquentFactory::class, function ($app) {
return EloquentFactory::construct(
$app->make(FakerGenerator::class), $this->app->databasePath('factories')
);
});
}
/**
* Register the queueable entity resolver implementation.
*
* @return void
*/
protected function registerQueueableEntityResolver()
{
$this->app->singleton(EntityResolver::class, function () {
return new QueueEntityResolver;
});
}
}
and finally created a class named QueryBuilder
in App/Override.最后在 App/Override 中创建了一个名为
QueryBuilder
的 class。 this is the problematic class:这是有问题的 class:
<?php
namespace App\Override;
use Illuminate\Support\Facades\Cache;
class QueryBuilder extends \Illuminate\Database\Query\Builder
{
private $Index = [];
public function useIndex($index = null)
{
$this->Index = $index;
return $this;
}
//@Override
public function get($columns = ['*'])
{
if ($this->Index) {
//Get the raw query string with the PDO bindings
$sql_str = str_replace('from `' . $this->from . '`', 'from `' . $this->from . '` USE INDEX (`' . $this->Index . '`) ', $this->toSql());
$sql_str = vsprintf($sql_str, $this->getBindings());
return parent::get($sql_str);
} else {
//Return default
return parent::get($columns);
}
}
}
The issues here are:这里的问题是:
The query builder is macroable so in your service provider you can probably do:查询生成器是可宏的,因此在您的服务提供商中,您可能可以这样做:
Illuminate\Database\Query\Builder::macro('tableWithIndex', function ($table, $index) {
$this->fromRaw($this->grammar->wrapTable($table)." USE INDEX (".$this->grammar->wrap($index).")");
});
Then you could use this:然后你可以使用这个:
DB::tableWithIndex('users', 'users');
within the macro $this
would refer to the query builder instance在宏
$this
中将引用查询构建器实例
Note that I have them both in one because you can potentially have multiple from
calls for the same query and it would be a mess trying to figure out what goes where请注意,我将它们合二为一,因为您可能会多次调用
from
一个查询,并且试图弄清楚什么去哪里会很麻烦
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.