Creating factories for a project I’m working on, I have a problem creating a belongsTo relationship.
In my Cards
table, I have 2 columns referencing the same relation :
Card->order->id
and Card->order->ref
(don’t ask me why, I don’t even know).
So, in my CardFactory
I need to be able to use the same instance of Order
for both $card->order_ref
and $card->order_id
. Using factory states, I did create the following state :
public function sold(int $userId) : Factory
{
$createdOrder = Order::factory()->forUser($userId)->create();
return $this->state(function (array $attributes) use ($createdOrder) {
return [
'state' => Card::STATE_SOLD,
'sold' => Carbon::now()->subDay(),
'addedincart' => Carbon::now()->subDay()->subHour(),
'selling_date' => Carbon::now()->subDay(),
'order_id' => $createdOrder->id,
'order_ref' => $createdOrder->ref,
];
});
}
and in my CardSeeder.php
:
public function run()
{
$user = User::query()->where("email", "[email protected]")->first();
Card::factory()->sold($user->id)->count(15)->create();
Card::factory()->selling()->count(15)->create();
}
The problem is, for each sold
state created, the same $createdOrder->id
is used.
How could I, for each row, use a different order ?