建表生成测试数据

2021-04-18  本文已影响0人  江河湖海琴瑟琵琶

一个表对应一个模型,数据迁移就是对数据库表结构的操作.

新建accounts表

命令行生成迁移文件
php artisan make:migration create_table_accounts --create=accounts

迁移文件中的方法
public function up()
    {
        Schema::create('accounts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('account');
            $table->string('password');
            $table->timestamps();
        });
    }

命令行运行迁移文件
php artisan migrate

建表完成 图片.png

生成测试数据

命令行创建对应model
php artisan make:model Models/Account

命令行创建模型工厂
php artisan make:factory AccountFactory

编辑模型工厂database\factories\AccountFactory.php

<?php
use Faker\Generator as Faker;
$factory->define(\App\Models\Account::class, function (Faker $faker) {
    return [
        //
        'account'=>$faker->phoneNumber,
        'password'=>encrypt($faker->randomNumber(6,true))
    ];
});

找到database\seeds\DatabaseSeeder.php文件
run方法内调用factory()方法调用模型

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        factory(\App\Models\Account::class,10)->create();
    }
}
命令行执行
php artisan db:seed
图片.png
上一篇 下一篇

猜你喜欢

热点阅读