在架构迁移中创建FULLTEXT字段

时间:2018-09-02 16:34:32

标签: laravel schema

我目前正在制作一个Laravel软件包,主要供内部项目使用,但我遇到了一点麻烦...

我正在为每个需要搜索的模型添加一个searchable全文列。我正在使用Laravel的本机迁移功能-

Schema::table('assets', function (Blueprint $table) {
    Searchable::migrateUp($table, 'moderated');
});

因此在moderated列之后调用了一种方法来部署迁移。这就是该方法的样子-

public function migrateUp(Blueprint $table, $after = null)
{

    // add our searchable column
    $table
        ->longText('searchable')
        ->after($after)->nullable();

    // ToDo: get indexing working on migration
    // add a fulltext index
    DB::statement(
        'ALTER TABLE ? ADD FULLTEXT fulltext_searchable (?)',
        [$table->getTable(), 'searchable']
    );

    // return our table
    return $table;
}

因此创建了一个可为空的长文本字段,然后尝试从中创建FULLTEXT索引。问题当然是在我运行语句时,可搜索列实际上还不存在。我仍然可以像在迁移文件中调用Searchable::migrateUp()一样简单的同时做些什么?

赞赏任何指针!克里斯。

1 个答案:

答案 0 :(得分:1)

我想我在编写此代码时是盲人的-您知道何时看不到简单解决方案过于复杂的解决方案吗?感谢@JonasStaudenmeir,心态和重构略有改变,我的解决方案如下-

我的迁移-

 /**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Searchable::migrateUp('assets', 'moderated');

}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Searchable::migrateDown('assets');
}

我的方法-

 /**
 * Creates searchable column on model table
 *
 * @param string      $table Table name to perform migration on
 * @param string|null $after Whether to add after a particular column
 *
 * @return void
 */
public function migrateUp($table, $after = null)
{

    // add to our schema
    Schema::table(
        $table,
        function (Blueprint $table) use ($after) {
            $table->longText($this->_searchableColumnKey)
                ->after($after)->nullable();
        }
    );

    // create our index
    \DB::statement("ALTER TABLE {$table} ADD FULLTEXT fulltext_searchable ({$this->_searchableColumnKey})");
}

/**
 * Removes searchable column on table
 *
 * @param Blueprint $table Requires blueprint
 *
 * @return void
 */
public function migrateDown($table)
{
    Schema::table(
        $table,
        function (Blueprint $table) {
            $table->dropColumn($this->_searchableColumnKey);
        }
    );
}

因此,我没有从架构中调用我的方法,而是从方法内部运行架构!

相关问题