laravel 迁移重新组织列顺序

问题描述 投票:0回答:7

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

laravel-4 eloquent fluent
7个回答
64
投票

尝试一下,希望它能帮助您找到正确的解决方案:

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

}

42
投票

如果您想在不破坏数据的情况下完成此操作,您可以在进行架构更新的同时迁移数据:

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

7
投票

我建议使用 DB::query('.. 原始 sql 查询 ..');并使用答案“How to move columns in a MySQL table?”中的查询


2
投票

试试这个

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。


0
投票

如果您有大量列,您需要使用 phpMyAdmin 重新排列您的出租车。有一个

Move columns
选项添加到
Structure
选项卡的底部。

在点击

Go
按钮之前,请使用
Preview SQL
按钮并复制查询。

接下来创建一个新的迁移并将其放入

up
函数中:

DB::statement(".... (copy the SQL here).... ");

快速又简单


0
投票

在较新的 Laravel 版本中,这可以完成工作。

    public function up(): void
    {
        Schema::table('example', function (Blueprint $table) {
            $table->date('foo')->after('bar')->change();
        });
    }

-17
投票

非常重要的注意事项

仅当您尚未启动您的应用程序(即尚未被任何真正用户使用)时才使用以下解决方案,因为以下解决方案将删除该列以及存储在其中的所有数据,并创建一个新的在您确定的列后空 具有相同名称的列。


假设您的列名称是

address

 并且您想要重新排序其位置,以便它位于另一个名为 
city
 的列之后,并且您的表名称是 
employees

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

php artisan migrate:make reorganize_order_of_column_address --table=employees
您可以根据需要仅更改 

reorganize_order_of_column_address

employees
,但保持命令的其余部分不变。

这将在

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"); }); }
    
© www.soinside.com 2019 - 2024. All rights reserved.