SyedKhizer
SyedKhizer

Reputation: 241

Category wise product sale laravel

I would to calculate the number of sale each category got and save it into an array as i have to display it in apex chart .

Here is a structure of my db

Category db:
category_name

Product db:
product_name;
category_id

OrderItem:
order_id;
product_id;
qty;

OrderItem relation :

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

I am bit confuse how to query that .

Upvotes: 0

Views: 560

Answers (1)

Héctor William
Héctor William

Reputation: 796

Well, to do that you probably should implement the Has Many Through relationship to get all orders made for each category, then you could make a method to count all items sold in that order, if that what you're after.

Here's how you could do that

in your Category model:

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

this will give you access to the collection of orders made with that category, then you just will call like this:

$category->orderItems;

You can use that in your methods to make your calculations.

To read more about this, check the documentation of has-many-through.

Upvotes: 1

Related Questions