laravel migration re-organising column order

后端 未结 4 898
再見小時候
再見小時候 2021-02-01 13:23

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 o

4条回答
  •  余生分开走
    2021-02-01 13:56

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

提交回复
热议问题