laravel - 使用现有数据创建新迁移 table

laravel - Create a new migration table with data from existing

我有一个用户 table,在类型列中有两种类型 'student' 或 'faculty'。 我想从用户 table 为教师和学生创建两个不同的 tables...

我想为教师和学生创建两个模型,但我无法提前考虑如何为这些模型填充 tables。

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name');
        $table->string('identif')->unique();
        $table->string('type');
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();

        //Add Primary Key

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('users');
}     }

最简单的方法是 运行 原始查询并将数据从用户 table 复制到其他 2 table,如果您使用 MySQL 然后像下面这样的东西可以工作:

DB::statement("INSERT INTO students (name, identif, email, password) SELECT (name, identif, email, password) FROM users WHERE type = ?", array('student'));

其他数据库应该提供类似的功能。

如果您不需要 Eloquent 模型逻辑是 运行 这些记录,则以上是可以的。否则只需获取 User 对象,创建新的 Student 或 Faculty 对象并保存新对象:

Users::all()->map(function($user) {
  if ($user->type == 'student') {
    Student::create($user->toArray());
  } else {
    Faculty::create($user->toArray());
  }
});

如果您希望每次创建 Users 对象时都创建一个新的 User of Faculty 对象,您可以使用 Eloquent 模型事件:

//User.php
protected static function boot() {
  parent::boot();

  static::created(function($user) {
    if ($user->type == 'student') {
      Student::create($user->toArray());
    } else {
      Faculty::create($user->toArray());
    }
  });
}