简体   繁体   English

如何扩展Laravel查询生成器?

[英]How to extend Laravel query builder?

I want to get Laravel database table's indexes. 我想获取Laravel数据库表的索引。

I know I can get them as below 我知道我可以按照以下方式获得它们

\DB::select("SHOW INDEX FROM $db_table_name WHERE non_unique = 1 AND column_name = '$db_column_name'");

But I think it's not good way. 但是我认为这不是一个好方法。 I want to get them like: 我想让他们像:

// this
\DB::getIndex($db_table_name, $db_column_name);

// Or this
\DB::table($db_table_name)->getIndex($db_column_name);

I think I have to extend query builder. 我想我必须扩展查询生成器。
Please tell me how to do. 请告诉我该怎么做。

Edit-- 编辑 -
I use 我用
Laravel Framework 5.6.39 Laravel框架5.6.39
PHP 7.2.17 PHP 7.2.17

Yes, you will need to extend the query builder, so you can place this code in your AppServiceProvider boot method, or if you have a custom service provider: 是的,您将需要扩展查询构建器,以便可以将此代码放置在AppServiceProvider boot方法中,或者如果您具有自定义服务提供程序:

use Illuminate\Database\Query\Builder; // at the top of the class

Builder::macro('getIndex', function($columnName){
   return $this->getConnection()
           ->select("show index from {$this->from} where non_unique = 1 and column_name='$columnName'");
});

Then to use it: 然后使用它:

DB::table('TABLE_NAME')->getIndex('COLUMN_NAME');

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM