php - 使用 Laravel 5 将数据从旧表转移到新表

标签 php laravel migration

是否可以将旧表中的数据复制到新表中?我们正在计划对数据库进行重大重新安排,将当前表中的所有数据传递到新创建的表中 表。

我们意识到处理新闻源等数据会很容易。这是我的迁移:

/*students table*/

    public function up()
        {
            Schema::create('students', function (Blueprint $table) {
                $table->increments('id');
                $table->string('lname');
                $table->string('mname')->nullable();
                $table->string('fname');
                $table->char('gender', 1);
                $table->date('date_of_birth');
                $table->string('address');
                $table->tinyInteger('yr_lvl');
                $table->string('contact_no');
                $table->text('about_me')->nullable();
                $table->text('education')->nullable();
                $table->text('achievements')->nullable();
                $table->text('seminars')->nullable();
                $table->text('organizations')->nullable();
                $table->tinyInteger('status')->default(1);
                $table->timestamps();
            });
        }

    /*newly created table works*/
    Schema::create('works', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('student_id')->unsigned()->nullable();
                $table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
                $table->text('about_me')->nullable();
                $table->timestamps();
            });

最佳答案

这是我对你的问题的想法:

1)创建迁移文件;

在该文件中的 up 函数中:

2)通过选择所需字段从旧表创建一个对象

现在

3)写入新表的迁移代码。

现在启动 foreach 循环并存储数据:

$oldData  = OLDTABLE::select('your_fields')->get();

Schema::create('works', function (Blueprint $table) {
                    $table->increments('id');
                    $table->integer('student_id')->unsigned()->nullable();
                    $table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
                    $table->text('about_me')->nullable();
                    $table->timestamps();
                });

foreach ($oldData as $data){
  $newData = new Work();
  $newData->student_id = $data->student_id
  $newData->save();
}

4) 运行迁移

关于php - 使用 Laravel 5 将数据从旧表转移到新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36395469/

相关文章:

PHP Regex 提取键值逗号分隔

php - mysql 中的行锁

windows - symfony2 Doctrine windows 到 linux 服务器迁移

mysql - SQLSTATE[42S02] : Base table or view not found: 1146 Table 'softwareproject.o_r_f_o_l_s' doesn't exist error in laravel

php - 在 Laravel 5.3 中执行原始查询

php - 在 Laravel 中执行迁移的向上和向下方法时运行特定代码

php - Doctrine 2 重写多对一关联

javascript - 使用谷歌云消息和服务 worker 的桌面推送通知

php - 带有 keyBy 的 Laravel 响应返回对象和数组

php - 对于 Laravel Eloquent 模型及其关系,如何实现由 UUID 组成的主键,而不是自动递增的整数?