Laravel 4 laravel迁移重新组织列顺序

Laravel 4 laravel迁移重新组织列顺序,laravel-4,eloquent,fluent,Laravel 4,Eloquent,Fluent,在表中创建新列时,可以使用->after('column name')指示它的位置。我如何创建一个迁移,以我想要的正确顺序对列重新排序?我建议使用DB::query(“…原始sql查询…”);并使用答案“非常重要的注释”中的查询 仅当您仍处于开发阶段且尚未启动应用程序时才使用以下解决方案,因为以下解决方案将删除列及其存储的所有数据,并在您确定的列后创建一个新的空的列 假设您的列名是address,您希望对其位置进行重新排序,使其位于另一个名为city的列之后,并且您的表名是employees

在表中创建新列时,可以使用->after('column name')指示它的位置。我如何创建一个迁移,以我想要的正确顺序对列重新排序?

我建议使用DB::query(“…原始sql查询…”);并使用答案“

非常重要的注释”中的查询

仅当
您仍处于开发阶段且尚未启动应用程序时才使用以下解决方案,因为以下解决方案将删除列及其存储的所有数据,并在您确定的列后创建一个新的空的


假设您的列名是
address
,您希望对其位置进行重新排序,使其位于另一个名为
city
的列之后,并且您的表名是
employees

在终端中键入下一个命令:

php artisan migrate:make reorganize_order_of_column_address --table=employees
您只能根据需要更改
重新组织\u列\u地址
员工
,但保留命令的其余部分

这将在
app/database/migrations
文件夹中生成一个迁移文件,打开它并将代码放入
up()
函数中,如下所示:

public function up()
{
    Schema::table('employees', function(Blueprint $table)
    {
        $table->dropColumn("address");
    });

    Schema::table('employees', function(Blueprint $table)
    {
        $table->string('address')->after("city");
    });
}

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

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

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

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");

}
试试这个

public function up()
{

    DB::statement("ALTER TABLE example CHANGE foo foo DATA_TYPE DATA_ATTRIBUTE(s) AFTER bar");
    DB::statement("ALTER TABLE example CHANGE foo foo INT(10) UNSIGNED NOT NULL AFTER bar");

}

或者,如果您懒得去理解SQL,您可以访问您的phpMyAdmin,单击您的数据库,单击您的表,单击“结构”选项卡,除了要移动的列之外,单击“更改”按钮,编辑“上次移动”列,单击“保存”按钮,然后复制SQL。

好主意,但我建议这样做:DB::语句(“…原始sql查询…”;值得注意的是,
foo DATE
中的
DATE
应更改为您正在使用的任何数据类型。请记住添加VARCHAR列的大小,例如:
DB::statement(“ALTER TABLE example MODIFY COLUMN foo VARCHAR(32)bar后的ALTER TABLE example MODIFY COLUMN foo VARCHAR(32));
这是一种非常好的黑客技术,即使在现在仍然有效。谢谢Sira,这种方法比中的方法有什么优势吗?这种方法似乎需要更多的处理能力和时间,但却拥有几乎同样多的投票权。破坏数据的迁移似乎是一种不好的做法。