artisan migrate命令创建数据库表并生成测试数据

1.先创建migration,

php artisan make:migration create_admin_table --create=admin

这样在database/migrations下就多了2018_05_23_012929_create_admin_table.php文件

然后在up方法里添加字段信息

public function up()
{
    Schema::create('admin', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

2.使用migrate命令生成表

php artisan migrate

数据库里就多了我创建的admin表了

3.为现有表新增字段

不可直接在原有migration文件里直接新增字段,而要新建一个migration文件

php artisan make:migration add_deleted_at_to_admin_table --table=admin


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

class AddDeletedAtToLikeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('admin', function (Blueprint $table) {
            //
            $table->timestamp('deleted_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('admin', function (Blueprint $table) {
            //
            $table->dropColumn('deleted_at');
        });
    }
}
在新增的文件里往admin表里添加deleted_at字段,重新执行php artisan migrate即可新增字段

4.生成测试数据

首先在database/factories下的ModelFactory中添加你要插入的字段和值

$factory->define(App\Doctors::class, function (Faker\Generator $faker) {
    $faker = \Faker\Factory::create('zh-CN');//设置faker,数据为中文
    return [
        'name' => $faker->name,
        'hospital' => $faker->randomElement(['北京协和医院','河北省人民医院','河北医科大学第一医院','河北医科大学第二医院']),
        'job_title' => $faker->randomElement(['主治医师','兼职','测试','认证医师']),
        'avatar' => $faker->imageUrl(),
        'intro' => $faker->sentence
    ];
});

方法一:

命令行输入

php artisan tinker

然后执行

factory(App\Doctors::class,20)->create()

即可向doctors表里添加20条数据

方法二:

factory(App\Doctors::class,20)->create()这几句写到seeds目录下的DatabaseSeeder.php的run方法中

public function run()
{
    Model::unguard();
    // $this->call(UserTableSeeder::class);
    Model::reguard();
    factory(App\Doctors::class,20)->create()
}

然后执行

php artisan db:seed

即可



你可能感兴趣的:(artisan命令)