Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

danimohamadnejad's avatar

one query to get list of data and total count and total sum?

hello I have following table: products id name price sold_count how can I paginate through products and to get list of data along with total sold_count of all products and also total number of products, all in one query? Product::withSum('sold_count')->withCount()->paginate(); thank you in advance

0 likes
1 reply
Sinnbeck's avatar

I don't think there is any way of doing that. You can think of the result of a query as a excel sheet. Each row is a result. So you would have the total on each and every line

Instead you can just get all rows, and calculate the numbers afterwards. You can then send these two numbers separately. You can get the data from the paginator using $results->items()

Hope it makes sense

1 like

Please or to participate in this conversation.