0

Let's say we have a website like Amazon, where users are also sellers. We have three models: User, Product, and Order.

Products have a user_id that represent the seller, Orders have a user_id that represent the buyer.

Each order is for one single product.

The following function will get me all of the orders, except the ones where a user purchased a product that they were selling. Then the orders are grouped by year and month.

$orders_per_month = Order::whereHas('product',function($q) {
  $q->whereRaw('products.user_id != orders.user_id');
})->get()->groupBy(function($v) {
  return Carbon::parse($v->created_at)->format('Ym');
});

But instead of a list of these orders for each year and month, I need the sum of the the "amount" property of these orders for each year and month.

1 Answer 1

1

Add a map to iterate each group and get the sum.

$orders_per_month = Order::whereHas('product',function($q) {
  $q->whereRaw('products.user_id != orders.user_id');
})->get()->groupBy(function($v) {
  return Carbon::parse($v->created_at)->format('Ym');
})->map(function ($group, $key) {
    return [$key => $group->sum('amount')];
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.