我正在制作一个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()
一样简单?
感谢任何指针!克里斯。
我认为在提出这个问题时我是代码盲目的 - 你知道什么时候你看不到过于复杂的简单解决方案吗?!由于@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);
}
);
}
因此,而不是我的方法被Schema调用,我只是从方法中运行模式而不是!