首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel数据迁移

Laravel数据迁移
EN

Stack Overflow用户
提问于 2014-05-06 23:35:17
回答 1查看 14.4K关注 0票数 23

是否有办法在Laravel中进行数据迁移?我已经找到了一些关于如何为数据库添加种子的说明,但它没有涵盖需要将一个字段拆分为多个字段或将多个字段合并为一个字段的情况。

一个可能的解决方案是查询数据库并更新循环中的每个记录。这种方法的问题是,在迁移(Django为此提供了一个解决方案。)期间,模型可能不会反映表模式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-07 00:28:53

Laravel的迁移内置于:) http://laravel.com/docs/migrations

简单地跑

代码语言:javascript
复制
php artisan make:migration migration_name_here

它将在app/数据库/迁移下创建一个迁移。然后,您可以在up()和down()方法中使用Laravel的数据库类。

以这个为例..。

代码语言:javascript
复制
class SplitColumn extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('table_name', function($table)
        {
            // Create new columns for table_name (1 column split into 2).
            $table->string('new_column');
            $table->string('new_column_b');
        });

        // Get records from old column.
        $results = DB::table('table_name')->select('old_column')->get();

        // Loop through the results of the old column, split the values.
        // For example, let's say you have to explode a |.
        foreach($results as $result)
        {
            $split_value = explode("|", $result->old_column);

            // Insert the split values into new columns.
            DB::table('table_name')->insert([
                "new_column"    =>  $split_value[0],
                "new_column_b"  =>  $split_value[1]
            ]);
        }

        // Delete old column.
        Schema::table('table_name', function($table)
        {
            $table->dropColumn('old_column');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('table_name', function($table)
        {
            // Re-create the old column.
            $table->string('old_column');
        });

        // Get records from old column.
        $results = DB::table('table_name')->select('new_column', 'new_column_b')->get();

        // Loop through the results of the new columns and merge them.
        foreach($results as $result)
        {
            $merged_value = implode("|", [$result->new_column, $result->new_column_b]);

            // Insert the split values into re-made old column.
            DB::table('table_name')->insert([
                "old_column"    =>  $merged_value
            ]);
        }

        // Delete new columns.
        Schema::table('table_name', function($table)
        {
            $table->dropColumn('new_column');
            $table->dropColumn('new_column_b');
        });
    }
}
票数 45
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23506286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档