无法在修补匠中使用Laravel Factory

问题描述

我无法在Laravel Tinker建立模型工厂。

// ItemFactory.php

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,'slug' => $this->faker->slug(5,true),'code' => $this->faker->words(5,'description' => $this->faker->sentence,'price' => $this->faker->randomNumber(1000,10000),'size' => $this->faker->randomElement(['Small','Medium','Large',]),];
    }
}

修补匠内部

>>> factory(App\Item::class)->create();

它抛出一个错误:

PHP致命错误:在Psy Shell中调用未定义的函数factory() 第1行的代码

解决方法

在Laravel 8.x release notes中:

雄辩的模型工厂已完全重写为基于类的模型 工厂,并得到了一流的关系支持。

从Laravel 8开始删除了全局factory()函数。相反,您现在应该使用model factory classes

  1. 创建工厂:
php artisan make:factory ItemFactory --model=Item
  1. 确保在模型中导入了Illuminate\Database\Eloquent\Factories\HasFactory特征:
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    use HasFactory;

    // ...
}
  1. 像这样使用它:
$item = Item::factory()->make(); // Create a single App\Models\Item instance

// or

$items = Item::factory()->count(3)->make(); // Create three App\Models\Item instances

使用create方法将它们持久保存到数据库中:

$item = Item::factory()->create(); // Create a single App\Models\Item instance and persist to the database

// or

$items = Item::factory()->count(3)->create(); // Create three App\Models\Item instances and persist to the database

要说的是,如果您仍然想为Laravel 8.x中的上一代模型工厂提供支持,则可以使用laravel/legacy-factories包。

,

经过documentation of Model Factory之后, Laravel 8版本进行了重大更改。

要在Laravel 8内的任何地方使用Model Factory:

  1. 在内部模型中,我们需要导入Illuminate\Database\Eloquent\Factories\HasFactory性状

  2. 用于实现工厂的新命令

App\Item::factory()->create();
,

在 laravel 8 中删除了默认路由命名空间。

尝试更改命令

factory(App\Item::class)->create();

\App\Models\Item::factory()->create(); 
\App\Models\Item::factory(10)->create(); \\If you want to create specify number of record then

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...