Laravel利用Factory和Seeder產生假資料

這裡主要有3個步驟

  1. Model跟Migration(設定資料的格式)
  2. Seeder(用來執行Laravel指令)
  3. Factory模型工廠(假資料都在這裡設定)

資料表模組

首先創建資料表模組,以及資料庫遷移

php artisan make:model Post --migration

創建完後,進入model裡面指定資料表

protected $table = 'post';

創建完後進入migration,設定資料型態

    public function up()
    {
        Schema::create('post', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title',100);
            $table->string('user_name',100);
            $table->string('keyword',100);
            $table->longText('abstract',100);
            $table->longText('content');
            $table->string('sort',10);
            $table->integer('permissions');
            $table->date('release_time');
            $table->timestamps();
        });
    }

設定完後執行指令進行創建資料

php artisan migrate

如果要刪除資料庫,執行底下指令

php artisan migrate:rollback

Seeder

產生Seeder檔,會產生在database/seeds目錄底下

php artisan make:seeder post_seeder

建立完Seeder後,預設裡面只有run函式

在裡面指定工廠關聯的模組及運行次數

reguard()主要是用来解除模型的批量填充限制

    public function run()
    {
    //指定工廠關聯的model及運行次數
        factory(Post::class, 10)->create();
        Post::reguard(); //解除模型的批量填充限制
    }

Factory模型工廠

產生Factory檔,預設產生在database/factories目錄底下

php artisan make:factory PostFactory

裡面的檔案,預設有定義東西,不過我們額外定義

factory裡面有提供Faker來讓我們建立假資料

更詳細的Faker資料請看這裡

https://github.com/fzaninotto/Faker#fakerprovideruuid

為了使用模組,我們要引用進來

use App\Post;

底下我們指定模組為我們創建的Post::class

$factory->define(Post::class, function (Faker $faker) {
    return [
        'title'=> $faker->word ,
        'user_name'=> $faker->name,
        'keyword'=> $faker->name,
        'user_name'=> $faker->name,
        'abstract'=> $faker->word,
        'content'=> $faker->text,
        'sort'=> $faker->word ,
        'permissions'=> $faker->numberBetween($min = 0, $max = 2),
        'release_time'=> $faker->date($format = 'Y-m-d', $max = 'now'),
    ];
});

設定完後就可以測試看看了

執行Seeding

這裡我們指定Seeder來執行

php artisan db:seed --class=post_seeder
Last modification:May 15th, 2019 at 06:02 pm