php - laravel - 使用现有数据创建新的迁移表

标签 php mysql laravel laravel-5 relational-database

我有一个用户表,类型列中有两种类型“学生”或“教师”。 我想从用户表中为教师和学生创建两个不同的表...

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

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

最佳答案

最简单的方法是运行原始查询并将数据从 users 表复制到其他 2 个表,如果您使用 MySQL,则可以使用以下方法:

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

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

如果您不需要为这些记录运行 Eloquent 模型逻辑,则上述内容是可以的。否则,只需获取用户对象,创建新的学生或教师对象并保存新对象:

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

如果您希望每次创建 Users 对象时都创建一个新的 User of Facilities 对象,您可以使用 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());
    }
  });
}

关于php - laravel - 使用现有数据创建新的迁移表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31356021/

相关文章:

php - 如何在 Laravel 中过滤后显示消息?

mysql - 大型数据库表的设计技巧?

mysql - 如何更新链接到多个表的 FK - Cascade on Update

php - Ajax 调用后 Javascript 不执行

php - 组合框人口

Mysqli - #1052 - 字段列表中的列 'id' 不明确

php - 在 Laravel 中使用多个 Redis 数据库

php - Laravel:左连接查询

php - 如何在 MySQL 中的到期日期后更新列?

php - Laravel/Lumen 事件监听器不监听