gpt4 book ai didi

php - 无法在 Tinker 中使用 Laravel Factory

转载 作者:行者123 更新时间:2023-12-03 09:49:24 27 4
gpt4 key购买 nike

我无法在 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 Fatal error: Call to undefined function factory() in Psy Shellcode on line 1

最佳答案

在 Laravel 8.x 中 release notes :

Eloquent model factories have been entirely re-written as class basedfactories and improved to have first-class relationship support.


全局 factory()从 Laravel 8 开始删除函数。相反,您现在应该使用 model factory classes .
  • 创建工厂:
  • php artisan make:factory ItemFactory --model=Item
  • 确保 Illuminate\Database\Eloquent\Factories\HasFactory特征已导入您的模型:
  • use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;

    class Item extends Model
    {
    use HasFactory;

    // ...
    }
  • 像这样使用它:
  • $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包裹。

    关于php - 无法在 Tinker 中使用 Laravel Factory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63824410/

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