laravel自动建mysql索引_让 Laravel 优雅地创建 MySQL 全文索引

最近在浏览社区话题的时候,看到了一位同仁发表的一篇教程:Laravel 5.3 下通过 migrate 添加 “全文索引” 的方法,突然想到自己之前也研究过这一话题,所以今天就和大家分享一下我的实现思路:如何更优雅地创建fulltext索引。

我非常喜欢Laravel框架的原因之一就是它的拓展性简直太赞了,所有框架本身未实现的功能你都可以自定义实现,而且可以实现得非常优雅。

其实,要想让添加全文索引这个动作变得更“优雅”一点,不外乎为Blueprint类添加一个fulltext方法,操作起来就像这样$table->fulltext('column');,这就与我们平时为字段添加unique索引一样方便了。我们先来看看预想效果:

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::table('posts', function (Blueprint $table) {

$table->fulltext(['title', 'content']);

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropFulltext(['title', 'content']);

}

Step 1 拓展Blueprint类

为了实现上述所预想的效果,显然我们要对Laravel的Illuminate\Database\Schema\Blueprint类进行拓展。这里所说的拓展,实际就是在继承原Blueprint的前提下定义一个新的Blueprint,并且在新的Blueprint类里面添加我们想要拓展的fulltext方法:

namespace Vendor\Package;

use Illuminate\Database\Schema\Blueprint as BaseBlueprint;

class Blueprint extends BaseBlueprint

{

/**

* Specify a fulltext index for the table.

*

* @param string|array $columns

* @param string $name

* @return \Illuminate\Support\Fluent

*/

public function fulltext($columns, $name = null)

{

return $this->indexCommand('fulltext', $columns, $name);

}

/**

* Indicate that the given fulltext key should be dropped.

*

* @param string|array $index

* @return \Illuminate\Support\Fluent

*/

public function dropFulltext($index)

{ <

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值