Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

n8udd's avatar
Level 12

How to Create/Associate/Sync with HasManyThrough?

I've got 5 models (Account, User, Order, Item, OrderItem) with the related tables:

accounts
  id
  name
  url
  ...etc

users
  id
  name
  email
  ...etc

orders
    id
    ordered_on
    dispatched_on
    discount_code
    ...etc

items
  id
  price
  brand
  ...etc

order_item
  order_id
  item_id
  size (nullable)
  colour (nullable)
  cost_price (nullable)

I started with a many-to-many relationship between order and item, but need to do a few things that were proving difficult.

I will occationally need to get the total items related to a user or account, so I've created a hasManyThrough relationship for Order and Item through the OrderItem model.

class Order extends Model {

  public function items(): hasManyThrough
  {
      return $this->hasManyThrough([
          Item::class,
          OrderItem::class,
          order_id, // Foreign key on the order_item table...
          id // Foreign key on the item table...
      ]);
  }

}

I'm trying to workout how I can create a new order with associated items.

I feel like it should be something similar to the following:

$user = User::find(1);
$items = Item::find(1, 2);

$user_order = $user->orders()->first()->items()->attach($items);

OR 

$user_order = $user->orders()->first()->items()->create($items);

OR

$user_order = $user->orders()->first()->items()->sync($items);

Is there a way through eloquent to create the data and associate it using the hasManyThrough relationship?

0 likes
2 replies
noplanman's avatar

@n8udd I'm looking for something similar too, have you managed to solve it?

n8udd's avatar
Level 12

I ended up making an OrderItem model, gave it relationships to order and item and then created the model as you would do normally.

Please or to participate in this conversation.