【问题标题】:Data migration transferring from old table into new table, with Laravel 5使用 Laravel 5 从旧表迁移到新表的数据迁移
【发布时间】:2016-07-23 13:41:40
【问题描述】:

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

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

/*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();
            });

【问题讨论】:

  • 您有具有不同数据结构的“旧”表,您需要将该数据传输到“新”表(具有不同结构)?
  • 不,我只是想将一些数据(about_me)复制到一个新表中......如果你能看到另一个表(作品)有一个关于我的字段和一个来自学生的外键

标签: php laravel migration


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-12-26
    • 2017-12-11
    • 1970-01-01
    • 2020-10-03
    • 2021-11-07
    • 2017-02-14
    • 2019-04-16
    • 2016-09-25
    相关资源
    最近更新 更多