【问题标题】:laravel - Create a new migration table with data from existinglaravel - 使用现有数据创建一个新的迁移表
【发布时间】:2015-08-27 18:19:22
【问题描述】:

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

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

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

【问题讨论】:

    标签: php mysql laravel laravel-5 relational-database


    【解决方案1】:

    最简单的方法是运行原始查询并将数据从 users 表复制到其他 2 个表,如果您使用的是 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());
        }
      });
    }
    

    【讨论】:

    • 不幸的是,我需要在这些记录上运行雄辩的模型逻辑。 @jedrzej.kurylo
    • 那么唯一的选择就是获取所有用户并为学生和教师创建新的雄辩对象。您可以在迁移文件中执行此操作。
    • 哇哦!我怎样才能做到这一点? :D 我希望每当用户表中有新条目时......取决于其类型的学生或教师......它应该自动添加到相应的表中......我们可以从 laravel 本身做到这一点......? :)
    • 嗯,你为什么需要那个?我以为你想摆脱用户表。为什么要在数据库中保存 2 个用户数据副本?一个在用户中,一个在学生/教师中。
    • 无论如何,我更新了答案以显示每次创建用户时如何创建学生/教师。
    猜你喜欢
    • 2018-05-22
    • 2015-12-25
    • 2014-06-24
    • 2016-03-25
    • 2023-01-06
    • 2016-02-28
    • 2014-05-03
    • 2014-08-03
    • 2014-12-26
    相关资源
    最近更新 更多