I have Order Model, which has products relationship and products have category relationship. I need to get a function in my model to get single product with a static category.
Im doing the next code in Order.php, my model, but i dont like it.
`` public function mainProduct() { foreach ($this->products as $product) if ($product->category_id == 1) return $product; }
public function products() {
return $this->hasMany(Product::class);
}
In Product.php
public function scopeOfCategory($query, $categoryId) {
return $query->where('category_id', $categoryId);
}
And then use it with:
$mainProduct = $order->products()->ofCategory(1)->get();
// or, if you only expect to get one
$mainProduct = $order->products()->ofCategory(1)->first();