Php 工厂中的附加参数添加到表插入命令中
在我的Laravel 5.8应用程序中,我使用database/factories/HostelReviewFactory.php中的定义创建工厂:Php 工厂中的附加参数添加到表插入命令中,php,laravel,laravel-5,factory,Php,Laravel,Laravel 5,Factory,在我的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'; } $p
$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') ) ,
];
});
并从seeder数据库/seeds/hostelReviewTableSeeder.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))
看起来$parentParams中的所有值都添加到了目标表的字段列表中,我不需要它,因为$parentParams
这些只是我想设置为工厂的参数。
怎么了?如果我正确理解您的需求, 您希望能够使用与旅馆有关系的工厂创建HosterView 传递给factory(App\HostelView::class,10)->create([…])的参数将作为特定的模型属性处理,并覆盖factory中的默认数据。 您需要的是:
- 定义将附加到审阅的默认宿舍
- 能够为评审注入特定的宿舍
$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]);
您的表格中是否有“家长宿舍id”列?这是否回答了您的问题?