laravel migration重新组织列顺序

use*_*986 28 fluent eloquent laravel-4

在表中创建新列时,可以使用 - > after('列名称)来指示它的去向.如何创建按我想要的正确顺序重新排序列的迁移?

Odi*_*der 24

试试这个,希望它能帮助您找到正确的解决方案:

public function up()
{

    DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");

}

public function down()
{

    DB::statement("ALTER TABLE example MODIFY COLUMN foo DATE AFTER bar");

}
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,`foo DATE`中的`DATE`应该更改为您正在使用的任何数据类型. (8认同)
  • 请记住添加 VARCHAR 列的大小,例如:`DB::statement("ALTER TABLE example MODIFY COLUMN foo VARCHAR(32) AFTER bar");` (2认同)

Rob*_*ert 22

如果要在不破坏数据的情况下执行此操作,则可以在执行架构更新的同时迁移数据:

use DB;

public function up()
{
    //Give the moving column a temporary name:
    Schema::table('users', function($table)
    {
        $table->renameColumn('name', 'name_old');
    });

    //Add a new column with the regular name:
    Schema::table('users', function(Blueprint $table)
    {
        $table->string('name')->after('city');
    });

    //Copy the data across to the new column:
    DB::table('users')->update([
        'name' => DB::raw('name_old')   
    ]);

    //Remove the old column:
    Schema::table('users', function(Blueprint $table)
    {
        $table->dropColumn('name_old');
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 与[另一个答案](/sf/ask/1423854491/#42581336)中的方法相比,这样做有什么优势吗?这种方式似乎需要更多的处理能力和时间,但票数几乎一样多。 (2认同)

Rob*_*ijn 6

我建议DB :: query('.. raw sql query ..'); 并使用答案" 如何移动MySQL表中的列? "中的查询

  • 好主意,但我推荐这个:DB :: statement('.. raw sql query ..'); (2认同)