使用Laravel 5将数据从旧表迁移到新表


Data migration transferring from old table into new table, with Laravel 5

是否可以将数据从旧表复制到新表?我们正在计划一个主要的数据库重组,将当前表中的所有数据传递给新创建的桌子

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

/*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) 创建迁移文件;

在你的文件中向上功能:

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) 运行迁移