Recipe-box 数据填充

2018-01-05  本文已影响0人  三仕贰號

生成填充器(完成之后可在 database/migrations 下看到创建的文档)

>php artisan make:seed UsersTableSeeder
>php artisan make:seed RecipesTableSeeder

修改 DatabaseSeeder.php 的 run方法(路径:database/seeds/DatabaseSeeder.php)

 public function run()
{
    $this->call(UsersTableSeeder::class);
    $this->call(RecipesTableSeeder::class);
}

编写填充器

修改UsersTableSeeder.php

<?php
use Illuminate\Database\Seeder;
use Faker\Factory;
use App\User;
class UsersTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Factory::create();
        User::truncate();
        foreach (range(1,10) as $i){
            User::create([
                'name' => $faker->name,
                'email' => $faker->email,
                'password' => bcrypt('password'),
                'api_token' => str_random(60)
            ]);
        }
    }
}

修改RecipesTableSeeder.php

<?php
use Illuminate\Database\Seeder;
use Faker\Factory;
use App\Recipe;
use App\RecipeIngredient;
use App\RecipeDirection;
class RecipesTableSeeder extends Seeder
{
    public function run()
    {
        $faker = Factory::create();
        RecipeDirection::truncate();
        RecipeIngredient::truncate();
        Recipe::truncate();
        foreach (range(1,10) as $i){
            $recipe = Recipe::create([
                'user_id' => $i,
                'name' => $faker->sentence,
                'description' => $faker->paragraph(mt_rand(5,15)),
                'image' => 'test.png'
            ]);
            foreach (range(1, mt_rand(3,12))as $j){
                RecipeIngredient::create([
                    'recipe_id' => $recipe->id,
                    'name' => $faker->word,
                    'qty' => mt_rand(1,12).' Kg'
                ]);
            }
            foreach (range(1, mt_rand(5,12)) as $k){
                RecipeDirection::create([
                    'recipe_id' => $recipe->id,
                    'description' => $faker->sentence
                ]);
            }
        }
    }
}

运行迁移

>php artisan migrate
>php artisan db:seed
//php artisan migrate:refresh
//php artisan db:seed
上一篇下一篇

猜你喜欢

热点阅读