'How to count order count based on the category?

I have Five tables. They are: category ,Product , product_categories, Order and order products

Category Table

id Category Title
1 Category One
2 Category Two

Product Table

id product Title
1 product One
2 product Two

Product Categories Table

id product_id category_id
1 1 2
2 2 1

Order Table

id Order Title
1 Order One
2 Order Two

Order Products table

id product_id order_id
1 1 2
2 2 1

So now, I want Category order count through product's product_categories table and Order's order_products table.

It would be very easy if product table have category_id and order table have product_id so that we can easily fetch order count through hasManyThrough relationship.

This is my code that i have tried but it only counts product item.

 $orders['topCategories'] = ProductCategory::with('childs.childs')->withCount(['products'=>function ($query) {
           
                $query->whereHas('orders', function ($query){
                    $query->where('status', true);
                });
        }]);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source