I have a hasOne relationship in that a Campaign hasOne Product
The Product belongsTo the Campaign.
In this particular case, in the products database table, there should only ever be one, unique reference to a campaign. I set the constraint on the database side to unique. My question is, when defining a factory, how do I ensure that it picks a unique Campaign, which was previously created by a seeder?
class ProductFactory extends Factory
{
protected $model = Product::class;
public function definition()
{
return [
//
'name' => $this->faker->sentence,
'description' => $this->faker->paragraph,
'campaign_id' => Campaign::inRandomOrder()->first()->id, # this won't work
];
}
It is obvious why Campaign::inRandomOrder()->first()->id won’t work. I don’t necessarily want to use a Campaign factory here to create a new Campaign either because there’s a lot of nuances in how each instance is created and I already take care of that in my CampaignSeeder
I am interested in just associating each Product created with a Campaign that has yet to be claimed when I seed. What’s the best way to approach this?
Advertisement
Answer
Assuming you have a relationship product in your campaign model
class ProductFactory extends Factory
{
protected $model = Product::class;
public function definition()
{
return [
//
'name' => $this->faker->sentence,
'description' => $this->faker->paragraph,
'campaign_id' => Campaign::doesntHave('product')->first()->id,
];
}
everytime it will get first campaign in your table that doesnt have a product