Reputation: 15
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
Reputation: 686
In this case you need to use belongsToMany
relation.
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
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