What happens of the pizza price(s) change over time - you don't store the price with the order?
Adding up unique users with total value
Hello, I have 3 tables
Users - id, name, email, phone Orders - id, user_id, pizza_id, small_pizza, medium_pizza, large_pizza Pizzas - id, name, description, small_pizza_price, medium_pizza_price, large_pizza_price.
I'm trying to make a view where I can display this table through a foreach: user - email - phone - total order value of all time
user - email - phone i can get through the Orders <-> Users models link as :
$order -> user -> name .
and I can get the total value of the orders through the Orders <-> Pizzas models
$order->small_pizza * $order->pizza->small_pizza_price +$order->mediu_pizza * $order->pizza->mediu_pizza_price +$order->large_pizza * $order->pizza->large_pizza_price
But now I want to sum them up somehow so I have unique clients and a total from all their orders. Right now I have clients with multiple orders and their total value instead of unique clients with total value of orders of all time.
Does anyone have any ideas/suggestions?
@claudio88 that is a move in the right direction, and will allow you to calculate an accurate total. Using the built-it withSum Builder method (and assuming you now have a total column on the orders table)
$users = User::withSum('orders', 'total')->get();
In the resulting Collection, each User instance will have a orders_sum_total property automatically included.
To my mind, a join would be more performant:
$users = User::selectRaw('users.*, SUM(orders.total) as total_orders')
->leftJoin('orders', 'orders.user_id', 'users.id')
->groupBy('orders.user_id')
->get();
In the resulting Collection, each User instance will have a total_orders property included.
I still am of the opinion that a pivot table with order details (described previously) would be the better approach
Please or to participate in this conversation.