Select from json column

Viewed 55

There is a task to obtain most ordered products from orders table for given period of time. Table have JSON column called details and ordered products IDs are stored there:

{
    products: [
        {
            id: 1,
            quantity: 2,
        },
        {
            id: 6,
            quantity: 1
        }
    ]
}

Currently, I'm solving it this way, which kind of inefficient:

Order::whereBetween('created_at', $period)
    ->get('details->products as details')
    ->flatMap(fn ($order) => $order->details)
    ->groupBy('id')
    ->map(fn ($products) => $products->sum('quantity'));

The result contains pairs, where key - product id, and value total count from orders:

[
    1 => 2,
    6 => 1,
];

Is it possible to query product id and quantity directly?

0 Answers
Related