gpt4 book ai didi

Laravel 8 + 修补匠 : How to create dummy data

转载 作者:行者123 更新时间:2023-12-05 08:37:38 25 4
gpt4 key购买 nike

在之前的 Laravel 版本中,我在 tinker 中使用了这个:

php artisan tinker
factory(App\Banana::class, 3)->create();

但是在 Laravel 8 中,它给出了这个错误:`PHP 错误:找不到类 'Database/Factories/bananaFactory'

请问如何使用 tinker 在 Laravel 8 中创建虚拟数据?谢谢。

最佳答案

您可以尝试以下步骤:

  1. 在您的 Banana 模型中添加了 HasFactory,如下所示:
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Banana extends Model
{
use HasFactory;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'description'
];
}

  1. 创建工厂
- php artisan make:factory BananaFactory --model=Banana
  1. 在生成 BananaFactory 后转到该路径:
<?php

namespace Database\Factories;

use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class BananaFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Banana::class;

/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'title' => $this->faker->title,
'description' => $this->faker->text,
];
}
}

  1. 之后运行这个命令:
 composer dump-autoload
  1. 然后打开终端并运行:
php artisan tinker
Banana::factory()->count(3)->create()

重要:这里是创建工厂相关的文档:

https://laravel.com/docs/8.x/database-testing#creating-factories

关于Laravel 8 + 修补匠 : How to create dummy data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64961793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com