使用查询生成器在 Laravel 中添加全文索引
Using query builder for adding fulltext index in Laravel
这是在MySQL中添加全文索引的查询:
ALTER TABLE `TableName`
ADD FULLTEXT INDEX `IndexName` (`ColumnName`);
但是如何使用 Laravel 查询生成器添加全文索引?
应该这样做:DB::statement
DB::statement('ALTER TABLE TableName ADD FULLTEXT INDEX IndexName (ColumnName)');
多个Columns/Fields
DB::statement('ALTER TABLE Database.TableName ADD FULLTEXT fulltext_index (Col_1, col_2, col_3)');
在 Laravel >= 6.15.0 上,您可以像这样扩展 Illuminate\Database\Schema\Grammars\MySqlGrammar
和 Illuminate\Database\Schema\Blueprint
类(例如,在 boot()
方法上 AppServiceProvider
):
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Grammars\MySqlGrammar;
use Illuminate\Support\Fluent;
Blueprint::macro('fulltext', function ($columns, $name = null, $algorithm = null)
{
return $this->indexCommand('fulltext', $columns, $name, $algorithm);
});
Blueprint::macro('dropFulltext', function ($index)
{
return $this->dropIndexCommand('dropIndex', 'fulltext', $index);
});
MySqlGrammar::macro('compileFulltext', function (Blueprint $blueprint, Fluent $command)
{
return $this->compileKey($blueprint, $command, 'fulltext');
});
并像这样在您的迁移中使用它:
Schema::table('flights', function (Blueprint $table) {
$table->fulltext(['name', 'airline']);
});
//reverse the migration
Schema::table('flights', function (Blueprint $table) {
$table->dropFulltext(['name', 'airline']);
});
这是在MySQL中添加全文索引的查询:
ALTER TABLE `TableName`
ADD FULLTEXT INDEX `IndexName` (`ColumnName`);
但是如何使用 Laravel 查询生成器添加全文索引?
应该这样做:DB::statement
DB::statement('ALTER TABLE TableName ADD FULLTEXT INDEX IndexName (ColumnName)');
多个Columns/Fields
DB::statement('ALTER TABLE Database.TableName ADD FULLTEXT fulltext_index (Col_1, col_2, col_3)');
在 Laravel >= 6.15.0 上,您可以像这样扩展 Illuminate\Database\Schema\Grammars\MySqlGrammar
和 Illuminate\Database\Schema\Blueprint
类(例如,在 boot()
方法上 AppServiceProvider
):
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Grammars\MySqlGrammar;
use Illuminate\Support\Fluent;
Blueprint::macro('fulltext', function ($columns, $name = null, $algorithm = null)
{
return $this->indexCommand('fulltext', $columns, $name, $algorithm);
});
Blueprint::macro('dropFulltext', function ($index)
{
return $this->dropIndexCommand('dropIndex', 'fulltext', $index);
});
MySqlGrammar::macro('compileFulltext', function (Blueprint $blueprint, Fluent $command)
{
return $this->compileKey($blueprint, $command, 'fulltext');
});
并像这样在您的迁移中使用它:
Schema::table('flights', function (Blueprint $table) {
$table->fulltext(['name', 'airline']);
});
//reverse the migration
Schema::table('flights', function (Blueprint $table) {
$table->dropFulltext(['name', 'airline']);
});