table insert command 添加工厂中的附加参数

Additive parameters in factory are added to table insert command

在我的 Laravel 5.8 应用程序中,我在 database/factories/HostelReviewFactory.php 中创建了具有定义的工厂:

$factory->define(App\HostelReview::class, function (Faker $faker, $parentParams) {
    $flag_status= 'N';
    if( rand(1,4) == 1) {
        $flag_status= 'R';
    }

    $parent_hostel_id= $parentParams['parent_hostel_id'];

    return [

        'hostel_id'             =>  $parent_hostel_id,
        'email_inquiried'       =>  $faker->safeEmail,

        'full_name'             => $faker->name,
        'status'                => 'A',
        'flag_status'           => $flag_status,
        'review'                => $faker->text,
        'stars_rating_type_id'  => rand(1,5),
        'created_at'            => $faker->dateTimeBetween(  '-2 years', 'now', config('app.timezone')  ) ,
    ];
});

和 运行 来自播种机 database/seeds/HostelReviewsTableSeeder.php :

factory(App\HostelReview::class, 10)->create([ 'parent_hostel_id' => 30 ]);

我收到错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'parent_hostel_id' in 'field list' (SQL: insert into `ad_hostel_reviews` (`hostel_id`, `email_inquiried`, `full_name`, `status`, `flag_status`, `review`, `stars_rating_type_id`, `created_at`, `parent_hostel_id`) values (30, beer.ozella@example.com, Jamel Konopelski, A, N, Quis mollitia voluptas occaecati corrupti ut. Commodi dolorem delectus architecto nesciunt voluptatem quos. Itaque natus adipisci dicta impedit sint. Alias inventore accusantium ea., 3, 2018-02-13 01:18:34, 30))

看起来 $paramParams 中的所有值都添加到目标 table 的字段列表中,我不需要它,因为 $paramParams 只是我想设置为工厂的参数。 怎么了?

如果我正确理解您的需求, 您希望能够使用与旅馆有关系的工厂创建 HostelReview

您传递给 factory(App\HostelReview::class, 10)->create([...]) 的参数将作为特定模型属性处理并覆盖默认数据该工厂。 您需要的是:

  • 定义将附加到评论的默认旅馆
  • 能够将特定旅馆添加到评论中

这就是 HostelReview 的样子:

$factory->define(App\HostelReview::class, function (Faker $faker) {
    $flag_status= 'N';
    if( rand(1,4) == 1) {
        $flag_status= 'R';
    }

    return [

        'hostel_id'             => function () {
            return factory(App\Hostel::class)->create()->id; // This will create a new Hostel and set the id in case you did not express in the caller the hostel_id to inject
        },
        'email_inquiried'       => $faker->safeEmail,
        'full_name'             => $faker->name,
        'status'                => 'A',
        'flag_status'           => $flag_status,
        'review'                => $faker->text,
        'stars_rating_type_id'  => rand(1,5),
        'created_at'            => $faker->dateTimeBetween(  '-2 years', 'now', config('app.timezone')  ) ,
    ];
});

对于第二点,您可以通过此调用覆盖默认的附加旅馆:

factory(App\HostelReview::class, 10)->create(['hostel_id' => 30]);