Skip to main content

Example 4. GROUP BY Multiple Tables

Premium
2 min read
Dmytro Sakharuk avatar

In the query, you count the number of purchased unique products. Obviously, if you are trying to calculate the total number of purchased products, then you need to sum up the quantity and make a left join.

$orders = DB::table('orders')
->selectRaw(
'users.name as user_name, sum(orders.total) as total, sum(order_product.quantity) as total_products'
)
->join('users', 'orders.user_id', '=', 'users.id')
->join('order_product', 'order_product.order_id', '=', 'orders.id', 'left')
->groupBy('user_name')
->get();
👍 1
Modestas avatar

You are right! These are 2 different statistics you might encounter. In one case, you care about the unique product count, while in other case - you care about the actual SKUs amount (not unique products) :)

For our goal it was just unique products, but in real life - you do see a variaty of calculations

Modestas avatar

Hi, I have updated the lesson and added an automated test with our repository link. This should solve the issue that we had here.

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.