Laravel框架数据迁移和填充

一、数据迁移
1、使用 Artisan 命令make:migration来创建一个新的迁移:

php artisan make:migration create_users_table

执行成功后会在database\migrations目录下生成如下格式的php文件
2016_05_05_060000_create_users_table.php

<?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('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } } 

迁移的顺序跟生成迁移文件的时间有关系。如果要修改表结构,比如说添加某个字段,需要在创建表之后执行,
比如说为users表添加软删除(也就是添加deleted_at字段)

php artisan make:migration update_users_table

在生成的php文件中添加如下代码

<?php

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

class UpdateUsersTable extends Migration {
    /** * Run the migrations. * * @return void */
    public function up() {
        Schema::table('users', function(Blueprint $table){
            // 软删除
            $table->softDeletes();
        });
    }

    /** * Reverse the migrations. * * @return void */
    public function down() {
        Schema::table('users', function(){
            $table->dropSoftDeletes();
        });
    }
}

二、数据填充
要生成一个填充器,可以通过 Artisan 命令make:seeder。所有框架生成的填充器都位于database/seeders目录:

php artisan make:seeder UsersTableSeeder

在生成的UsersTableSeeder.php中

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder{
    /** * 运行数据库填充 * * @return void */
    public function run() {
        DB::table('users')->insert([
            'name' => str_random(10),
            'email' => str_random(10).'@gmail.com',
            'password' => bcrypt('secret'),
        ]);
    }
}

在DatabaseSeeder类中,你可以使用call方法执行额外的填充类,

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder {
    /** * Run the database seeds. * * @return void */
    public function run() {   // 取消批量插入限制
        Model::unguard();
        $this->call(UsersTableSeeder::class); } } 

最后执行

php artisan db:seed
// 指定某个表的类名
// 指定类名后不需要在DatabaseSeeder.php中添加call方法
php artisan db:seed --class=UsersTableSeeder

你可能感兴趣的:(laravel框架)