user13011043
user13011043

Reputation:

How to count the orders of one product?

I have products , orders and third pivot table product_order(product_id , order_id), I need to count the orders of the product based on created_at

my shut:

public function product_chart(Product $product)
{
        $orders = $product->whereHas('orders', function ($query)  {
                    $query->whereMonth('created_at', '04');
                })->count();
    dd($orders);
}

The output gives the number of products :(

of course, I have a relation in a product called (orders) and in Order called (products)

So I need to count the orders of the product based on the created_at of order!

Upvotes: 0

Views: 351

Answers (1)

Elias Soares
Elias Soares

Reputation: 10254

That's because you are counting the products.

You can simply do this:

$ordersCount = $product->orders()->count();

But since you are applying some conditions, you need to append the where clause:

$ordersCount = $product->orders()->whereMonth('created_at', '04')->count();

Also there's a simpler way doing it according to Laravel Documentation:

use Illuminate\Database\Eloquent\Builder;

$posts = App\Post::withCount(['votes', 'comments' => function (Builder $query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;

Upvotes: 2

Related Questions