12

我无法在 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, true),
            'description' => $this->faker->sentence,
            'price' => $this->faker->randomNumber(1000, 10000),
            'size' => $this->faker->randomElement(['Small', 'Medium', 'Large',]),
        ];
    }
}

修补匠内部

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

它给我一个错误:

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

4

3 回答 3

19

在 Laravel 8.x发行说明中

Eloquent 模型工厂已完全重写为基于类的工厂,并改进为具有一流的关系支持。

factory()从 Laravel 8 开始,全局函数已被删除。相反,您现在应该使用模型工厂类

  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包。

于 2020-09-12T11:30:40.560 回答
14

在浏览了Model Factory 的文档后, Laravel 8 版本发生了重大变化。

在 Laravel 8 中的任何地方使用模型工厂:

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

  2. 实施工厂的新命令

App\Item::factory()->create();
于 2020-09-10T07:09:12.713 回答
12

在 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
于 2021-01-31T16:33:33.460 回答