guidocella/eloquent-populator

为 Eloquent 模型工厂猜测属性

v3.0.5 2024-03-14 11:22 UTC

README

此包通过从列名和类型中猜测最佳的 Faker 格式化器,为 Laravel 模型工厂提供默认属性。例如,如果列名为 first_name,它将使用 $faker->firstName()。如果不能通过列名猜测,将通过列的类型猜测格式化器;例如,对于 VARCHAR 列,它将使用 $faker->text(),对于 TIMESTAMP 将使用 Carbon 实例。还将创建已定义的 BelongsTo 关系的模型。此外,如果您使用 Multilingual 包,对于可翻译属性,Populator 将为每个配置的本地化生成具有不同值的数组。

与一次生成工厂的包相比,您通常不需要在更改表定义时更新您的工厂,并且它们将非常小。

安装

使用 Composer 安装包

composer require --dev guidocella/eloquent-populator

模型工厂集成

在您的工厂的 definition 方法中调用 Populator::guessFormatters($this->modelName()) 以获取包含猜测格式化器的数组。您可以将这些与具有不准确的猜测格式化器的自定义属性合并。

use GuidoCella\EloquentPopulator\Populator;

...

public function definition(): array
{
    return [...Populator::guessFormatters($this->modelName()), ...[
        'avatar' => $this->faker->imageUrl()
    ]];
}

如果您执行 php artisan stub:publish,您可以在 factory.stub 中包含对 Populator 的调用,以便 php artisan make:factory 会添加它。

猜测模型格式化器一次后,它们将缓存在不同测试的静态属性中。

播种

在播种您的数据库之前,您将想要调用 setSeeding()

public function run()
{
    Populator::setSeeding();

它的作用是,可空列有50%的机会被设置为 null 或猜测的格式化器。

测试

如果没有调用 setSeeding(),则可空列始终会设置为它们的猜测格式化器。这个想法是简化这样的测试

public function testSubmitWithoutName() {
    $user = User::factory()->make(['name' => null]);
    // test that submitting a form with $user's attributes causes an error
}

public function testSubmitWithCorrectName() {
    $user = User::factory()->make();
    // no need to specify the correct formatter for name since it can't be null
    // test that submitting a form with $user's attributes is succesful
}

另一方面,使用 null 属性播种数据库让您能够注意到 Trying to get property of non-object 错误。