最近在浏览社区话题的时候,看到了一位同仁发表的一篇教程: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)
{ <