欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

laravel seeder 数据填充

程序员文章站 2022-03-10 09:05:18
...

1:生成一个模型

$ php artisan make:model Post -m

2:填写posts的迁移表的字段内容

Schema::create('posts', function (Blueprint $table) {
 $table->increments('id');
 $table->string("title");
 $table->string("content");
 $table->integer('view_count')->unsigned();
 $table->timestamps();
});

3:新建一个填充类

php artisan make:seeder PostTableSeeder

4:在DatabaseSeeder类run()方法中,使用call方法获取要运行的填充器类:

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;


class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();
        $this->call('PostTableSeeder');
        Model::reguard();

    }
}

5:填写新建的类

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;


class PostTableSeeder extends Seeder
{
    public function run()
    {
        App\Post::truncate();
        factory(App\Post::class, 1000)->create();
    }
}

6:文件目录\database\factories\ModelFactory.php添加迁移内容

$factory->define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->sentence,
        'content' => $faker->paragraph,
        'view_count' => 0
    ];
});
laravel seeder 数据填充