DanielGB
DanielGB

Reputation: 15

hasManyThrough relationship in Laravel 5.8

I have the following struct:

Order
 id

Order_Products
 id
 order_id
 product_id

Products
 id

Im trying to use hasManyTrough (https://laravel.com/docs/5.8/eloquent-relationships#has-many-through).

I have something like

class Order extends Model{
...
public function products()
{
    return $this->hasManyThrough('App\Product', 'App\OrderProduct', 'product_id', 'id', 'order_id', 'id');
}
...
}

I can not make it work. I'm confused, can someone help me.

Upvotes: 0

Views: 799

Answers (2)

Mgorunuch
Mgorunuch

Reputation: 686

In this case you need to use belongsToMany relation.


A little bit about Has Many Through.

Tables:

Product
 id

Order
 id
 product_id

Order_Category
 id
 order_id

in this case you can get Order Categories for Product

class Product {
  // ...

  order_categories() {
    return $this->hasManyThrough('App\Post', 'App\User');
  }

  // ...
}

Laravel doing something like this.

$orderIds = Order::query()
  ->where('product_id', $product->id)
  ->get(['id'])
  ->pluck('id');

$orderCategories = OrderCategory::query()
  ->whereIn('order_id', $orderIds)
  ->get();

Upvotes: 2

DanielGB
DanielGB

Reputation: 15

Thanks to Tim Lewis, I needed belongsToMany, cause order_products is pivot table. Something like this.

public function products()
{
    return $this->belongsToMany('App\Product', 'order_products', 'order_id', 'product_id');
}

Upvotes: 0

Related Questions