【问题标题】:How to insert data to database using seeder in Laravel?如何在 Laravel 中使用播种器将数据插入数据库?
【发布时间】:2023-01-11 16:45:46
【问题描述】:

我有播种机的问题。我的数据没有插入到数据库中。表 customers 已创建,但数据未插入数据库。下面我展示代码。我用 php artisan migrate:fresh --seed 移民

 public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('first_name', 20);
            $table->string('last_name', 30);
            $table->string('email')->unique();
            $table->string('phone_number')->unique();
            $table->timestamps();
        });
    }

模型

class Customer extends Model
{
    use HasFactory;

    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'phone_number'
    ];
}

工厂

class CustomerFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'first_name'   => fake()->firstName(),
            'last_name'    => fake()->lastName(),
            'email'        => fake()->unique()->safeEmail(),
            'phone_number' => fake()->unique()->phoneNumber()
        ];
    }
}

播种机

class CustomersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Customer::factory(20)->create();
    }
}

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    DatabaseSeeder class 中,您必须调用该方法来执行其他种子类。

    /**
     * Run the database seeders.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            CustomersTableSeeder::class,
           
        ]);
    }
    

    根据官方文档:

    在 DatabaseSeeder 类中,您可以使用 call 方法来 执行额外的种子类。使用 call 方法可以让你 将你的数据库分解成多个文件,这样就没有一个 播种机类变得太大。调用方法接受一个数组 应该执行的播种器类:

    参考:Calling Additional Seeders

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 2018-08-06
      • 2014-03-01
      • 2015-09-25
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多