簡體   English   中英

laravel-使用現有數據創建新的遷移表

[英]laravel - Create a new migration table with data from existing

我的用戶表的類型列中有兩種類型的“學生”或“教師”。 我想從用戶表中為教師和學生創建兩個不同的表...

我曾想為教職員工和學生創建兩個模型,但是我不能在如何為這些模型填充表格方面做任何思考。

<?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模型邏輯,則可以使用上述方法。 否則,只需獲取用戶對象,創建新的Student或Faculty對象並保存新對象:

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

如果要在每次創建Users對象時創建一個新的Faculty User對象,則可以使用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());
    }
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM