如何解决无法在修补匠中使用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。
- 创建工厂:
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包。
,经过documentation of Model Factory之后, Laravel 8版本进行了重大更改。
要在Laravel 8内的任何地方使用Model Factory:
-
在内部模型中,我们需要导入
Illuminate\Database\Eloquent\Factories\HasFactory
性状 -
用于实现工厂的新命令
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