sandersjj's avatar

Factory for pivot table

I have 3 Models:

  • Order
  • OrderItem
  • Product

An order has many order items. And each order Item has a product. So an OrderItem consists of a product and a quantity etc.

I am trying to create an order with 70 items in a factory.

So I have been doing it this way:

   $order = Order::factory()
        ->has(OrderItem::factory(70))
        ->has(Product::factory())
        ->create([
            'sent' => false,
        ]);

However I get this error:

FAILED Tests\Feature\OrderTest > it Can successfully open big orders > TypeError OrderTest::{closure}(): Argument #2 ($product) must be of type App\Models\Product, App\Models\Order given, called in /Users/myuser/prive/stocks /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php

How Can I solve this?

Thanks

0 likes
3 replies
aleahy's avatar

The way you have this constructed your creation, it looks like the Order has the product model.

The has(Product::factory()) needs to be tied to the OrderItem.

$order = Order::factory()
    ->has(OrderItem::factory(70)->has(Product::factory()))
    ->create([
        'sent' => false,
    ]);
sandersjj's avatar

Hey,

Thanks for the reply.

I have tried it but then I got this error:

  SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: order_items.product_id (Connection: sqlite, SQL: insert into "order_items" ("quantity", "delivered_quantity", "reference", "type", "order_id", "updated_at", "created_at") values (57, 2, 559328, stock, 1, 2024-02-25 12:04:21, 2024-02-25 12:04:21))
aleahy's avatar

That says that one of your fields in your database is not allowed to be null, but you haven't given it a value. Is one of the fields missing in order_items?

Please or to participate in this conversation.