0
votes

I have the following structure:

orders id name

products id name

items id order_id product_id quantity

The relationships are as follows:

Order

public function items(){
 return $this->hasMany(Item::class)
}

public function products(){
 return $this->hasManyThrough(Product::class, Item::class);
}

Item

public function order(){
 return $this->belongsTo(Order::class);
}

public function product(){
 return $this->belongsTo(Product::class);
}

Product

public function items(){
 return $this->hasMany(Item::class);
}

I wish to get all products for the order doing something like this: $order->items()->products()->get() using the hasManyThrough method, but I must be doing it wrong since it tries to look for item_id in the products table.

1

1 Answers

0
votes

I realized that I do not need many through, I just need to use items table as a pivot table, defining the relationship on the Order model just like this:

public function products(){
 return $this->belongsToMany(Product::class, 'items');
}