代码之家  ›  专栏  ›  技术社区  ›  Chris

在架构迁移中创建全文字段

  •  0
  • Chris  · 技术社区  · 8 年前

    我正在制作一个主要用于内部项目使用的Laravel包,但我遇到了一个小问题。。。

    我在添加一个 searchable

    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;
    }
    

    所以创建了一个可为null的长文本字段,然后我尝试从中创建一个全文索引。当然,问题是在我运行语句时,可搜索列实际上还不存在。有什么办法我可以做到这一点,而它仍然是简单的用户调用 Searchable::migrateUp() 在他们的迁移文件中?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Chris    8 年前

    我想当我想到这个的时候,我是个代码盲——你知道吗,当你看不到简单的解决方案的过于复杂的时候?!由于@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调用的,而是从方法内部运行Schema!