商品工厂
public function definition()
{
return [
'user_id'=>rand(1,100),
'title'=>$this->faker->text(30),
'body'=>$this->faker->text(30),
];
}
}商品型号
Schema::create('goods', function (Blueprint $table) {
$table->id();
$table->integer('user_id');
$table->text('title');
$table->text('body');
$table->timestamps();
GoodsTableSeeder
public function run()
{
DB::table('goods')->factory()->times(50)->create();
}
Database\Siders\GoodsTableSeeder对未定义方法Illuminate\Database\Query\Builder::factory((的调用
以下是一些让工厂在laravel 8.x 中工作的快速指南
- 在Goods Factory类中声明$model属性:
protected $model = Goods::class;
- 在商品模型类中使用
HasFactory
特性
use IlluminateDatabaseEloquentFactoriesHasFactory;
- 在模型类上使用factory((方法生成模型实例或为数据库种子:
Good::factory()->count(15)->create();
- 如果使用种子程序,请确保将目录
database/seeds
重命名为database/seeders
,并在composer.json
中按如下方式更改自动加载
"autoload": {
"psr-4": {
"App\": "app/",
"Database\Factories\": "database/factories/",
"Database\Seeders\": "database/seeders/"
}
},
Laravel 8.x改变了使用工厂的方式,有关更多详细信息,您可以阅读以下文档:https://laravel.com/docs/8.x/upgrade#model-工厂https://laravel.com/docs/8.x/database-testing#defining-模型工厂
我希望以上内容能对你有所帮助,如果有什么不清楚的地方可以随时询问。