php – Laravel数据迁移

php – Laravel数据迁移,第1张

概述有没有办法在Laravel中进行数据迁移? 我已经找到关于如何种子数据库的一些说明,但不包括我需要将一个字段分割成多个字段或将多个字段合并为一个的情况. 一个可能的解决方案是查询数据库并更新循环中的每个记录.这种方法的问题是模型可能不会在迁移期间反映表模式(Django provides a solution for this). Laravel已经建成了:) http://laravel.com 有没有办法在Laravel中进行数据迁移?
我已经找到关于如何种子数据库的一些说明,但不包括我需要将一个字段分割成多个字段或将多个字段合并为一个的情况.

一个可能的解决方案是查询数据库并更新循环中的每个记录.这种方法的问题是模型可能不会在迁移期间反映表模式(Django provides a solution for this).

Laravel已经建成了:) http://laravel.com/docs/migrations

只需运行

PHP artisan migrate:make migration_name_here

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

以此为例…

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

以上是内存溢出为你收集整理的php – Laravel数据迁移全部内容,希望文章能够帮你解决php – Laravel数据迁移所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1258438.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存