laravel migration re-organising column order

五迷三道 提交于 2019-12-31 17:51:16

问题


When you create a new column in a table you can use the ->after('column name') to dictate where it goes. How can I create a migration that re-orders the columns in the right order I want?


回答1:


Try this, hope it help you to find right solution:

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

}



回答2:


If you want to do it without destroying data, you could migrate the data across at the same time you do the schema update:

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



回答3:


I would suggest a DB::query('.. raw sql query ..'); and use the query from the answer "How to move columns in a MySQL table?"




回答4:


Suppose your column name is address and you want to reorder its position so that it comes after another column called city, and your table name is employees.

In your terminal type the next command:

php artisan migrate:make reorganize_order_of_column_address --table=employees

You may only change reorganize_order_of_column_address and employees according to your needs, but keep the rest of the command as it is.

This will generate a migration file in app/database/migrations folder, open it and put your code inside the up() function like this:

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

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

Note that this method will delete the column and all data that was stored in it, and will create a new column with the same name after the column you detect, and the newly created one will be empty.

This way worked for me in Laravel 4.2, and it may also work in Laravel 5 but with some changes in the commands that you need to type in the terminal.



来源:https://stackoverflow.com/questions/20340778/laravel-migration-re-organising-column-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!