我正在使用[Nwidart] [1]模块软件包,并且正在尝试使用工厂创建播种机。但是,当我尝试运行php artisan db:seed
时,出现此错误
调用未定义函数Modules \ Products \ Database \ Seeders \ factory()
这是我的ProductsDatabaseSeeder.php
<?php
namespace Modules\Products\Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Modules\Products\Models\Product;
class ProductsDatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
factory(Product::class, 10)->create();
}
}
我的ProductFactory
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Faker\Generator as Faker;
use Modules\Products\Models\Product;
$factory->define(Product::class, function (Faker $faker) {
return [
'title' => $this->faker->title,
'price' => $this->faker->randomNumber(3),
];
});
我的Product.php
<?php
namespace Modules\Products\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [];
}
完全错误
Call to undefined function Modules\Products\Database\Seeders\factory()
at Modules/Products/Database/Seeders/ProductsDatabaseSeeder.php:25
21▕
22▕
23▕
24▕
➜ 25▕ $product = factory(Product::class, 10)->create();
26▕
27▕
28▕ }
29▕ }
+8 vendor frames
9 database/seeders/DatabaseSeeder.php:20
Illuminate\Database\Seeder::call()
+24 vendor frames
34 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
这是我改变后得到的
factory(Product::class, 10)->create();
到
Product::factory()->count(10)->create();
Class 'Database\Factories\Modules\Products\Models\ProductFactory' not found
at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php:656
652▕ public static function factoryForModel(string $modelName)
653▕ {
654▕ $factory = static::resolveFactoryName($modelName);
655▕
➜ 656▕ return $factory::new();
657▕ }
658▕
659▕ /**
660▕ * Specify the callback that should be invoked to guess factory names based on dynamic relationship names.
+1 vendor frames
2 Modules/Products/Database/Seeders/ProductsDatabaseSeeder.php:25
Modules\Products\Models\Product::factory()
+8 vendor frames
11 database/seeders/DatabaseSeeder.php:21
Illuminate\Database\Seeder::call()
[1]: https://nwidart.com/laravel-modules/v6/introduction
答案 0 :(得分:0)
从Laravel 8开始,您可能会用到-使用HasFactory特性-您将需要调用
Product::factory()->create()
为了运行工厂