Laravel 9工厂并创建相关的1:1型号
我想使用Laravel工厂在我的测试环境中填充一些虚拟数据。我有一个位置模型和一个位置尾声模型,它们具有1:1的关系,只要创建一个新的位置,就需要在locationDetails表中创建记录。
我该如何在工厂中进行此操作,以使每个位置记录的 1个位置通讯记录。
这是我在Databaseseeder类中的内容:
if(env('APP_ENV') === 'local') {
Client::factory()->count(25)->create();
Location::factory()->count(30)->create();
}
我的位置工厂定义:
public function definition()
{
return [
'name' => $this->faker->company,
'client_id' => Client::all()->random()->id,
'location_status_id' => LocationStatus::all()->random()->id,
'address' => $this->faker->streetAddress,
'city' => $this->faker->city,
'state' => $this->faker->StateAbbr,
'zip_code' => $this->faker->numerify('#####'),
'phone' => $this->faker->numerify('###-###-####'),
'email' => $this->faker->safeEmail,
'is_onboarding_completed' => 1,
];
}
Laravel看起来有一个工厂的AfterCreate()回调,但我不清楚如何完成此操作。
I'd like to use Laravel factories to populate some dummy data in my test environment. I have a Locations model and a LocationDetails model, which have a 1:1 relationship and a record needs to be created in the LocationDetails table whenever a new Location is created.
How can I do this in a factory such that there's exactly 1 LocationDetails record for each Location record.
Here's what I have in my DatabaseSeeder class:
if(env('APP_ENV') === 'local') {
Client::factory()->count(25)->create();
Location::factory()->count(30)->create();
}
My location factory definition:
public function definition()
{
return [
'name' => $this->faker->company,
'client_id' => Client::all()->random()->id,
'location_status_id' => LocationStatus::all()->random()->id,
'address' => $this->faker->streetAddress,
'city' => $this->faker->city,
'state' => $this->faker->StateAbbr,
'zip_code' => $this->faker->numerify('#####'),
'phone' => $this->faker->numerify('###-###-####'),
'email' => $this->faker->safeEmail,
'is_onboarding_completed' => 1,
];
}
It looks like Laravel has an afterCreate() callback for a factory, but I'm just not clear on how to accomplish this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这项工作
是否可以在 Location -factory 上定义一个状态
,然后像
Does this work
Or you can have a state defined on the LocationFactory
And then use it like