在 Laravel 5.5 中生成工厂

Generate Factory in Laravel 5.5

我运行下面的命令

php artisan make:factory AddressFactory

我低于结果

$factory->define(Model::class, function (Faker $faker) {

但我想得到如下结果

$factory->define(App\Address::class, function (Faker $faker) {

我该怎么办?

如果你想要make:factory命令为现有模型生成工厂class,你需要告诉它使用哪个模型--型号 选项:

php artisan make:factory AddressFactory --model="App\Address"

对于Laravel 8

使用 artisan 命令,您不再需要指定模型。通过在模型中自动包含工厂特性,Laravel 自动使工厂方法可用于相应的模型。

所以只有:

php artisan make:factory AddressFactory

然后在播种器或测试中调用模型就足够了。

例如:

App\Models\Address::factory(10)->create();

Model & Factory Discovery Conventions

Once you have defined your factories, you may use the static factory method provided to your models by the Illuminate\Database\Eloquent\Factories\HasFactory trait in order to instantiate a factory instance for that model.

The HasFactory trait's factory method will use conventions to determine the proper factory for the model the trait is assigned to. Specifically, the method will look for a factory in the Database\Factories namespace that has a class name matching the model name and is suffixed with Factory. If these conventions do not apply to your particular application or factory, you may overwrite the newFactory method on your model to return an instance of the model's corresponding factory directly: