当前位置 > it书童 > laravel > 正文

laravel6生成并填充假数据

laravel it书童 2020-02-08 10:19:42 0赞 0踩 101阅读 0评论

以生成话题数据为例

生成填充文件

$ php artisan make:seed UsersTableSeeder

database/factories/TopicFactory.php

<?php

use Faker\Generator as Faker;

$factory->define(App\Models\Topic::class, function (Faker $faker) {

    $sentence = $faker->sentence();

    // 随机取一个月以内的时间
    $updated_at = $faker->dateTimeThisMonth();

    // 传参为生成最大时间不超过,因为创建时间需永远比更改时间要早
    $created_at = $faker->dateTimeThisMonth($updated_at);

    return [
        'title' => $sentence,
        'body' => $faker->text(),
        'excerpt' => $sentence,
        'created_at' => $created_at,
        'updated_at' => $updated_at,
    ];
});

database/seeds/TopicsTableSeeder.php

<?php

use Illuminate\Database\Seeder;
use App\Models\Topic;
use App\Models\User;
use App\Models\Category;

class TopicsTableSeeder extends Seeder
{
    public function run()
    {
        // 所有用户 ID 数组,如:[1,2,3,4]
        $user_ids = User::all()->pluck('id')->toArray();

        // 所有分类 ID 数组,如:[1,2,3,4]
        $category_ids = Category::all()->pluck('id')->toArray();

        // 获取 Faker 实例
        $faker = app(Faker\Generator::class);

        $topics = factory(Topic::class)
                        ->times(100)
                        ->make()
                        ->each(function ($topic, $index)
                            use ($user_ids, $category_ids, $faker)
        {
            // 从用户 ID 数组中随机取出一个并赋值
            $topic->user_id = $faker->randomElement($user_ids);

            // 话题分类,同上
            $topic->category_id = $faker->randomElement($category_ids);
        });

        // 将数据集合转换为数组,并插入到数据库中
        Topic::insert($topics->toArray());
    }
}

注册数据填充 database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $this->call(UsersTableSeeder::class);
        $this->call(TopicsTableSeeder::class);
    }
}

生成数据

$ php artisan db:seed

清空并生成数据

$ php artisan migrate:refresh --seed

指定填充文件

$ php artisan db:seed --class=ArticlesTableSeeder
转载须注明出处:https://www.itshutong.com/articles/408/laravel6-generates-and-populates-false-data
标签: laravel6
关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
发表评论
我有句话,不知当讲不当讲?
要讲之前请先 登录