-1

I have a User model, who hasMany categories and category hasMany posts and post hasOne Product

Now I want to sum all of the product->price of Auth::user()

how can i do that withSum or withCount function. in Laravel

TylerH
  • 20,799
  • 66
  • 75
  • 101
Rajib Bin Alam
  • 353
  • 1
  • 4
  • 16

1 Answers1

2

Since your question doesnt present any details, I will assume that you have all the relations well set up.

You can get the sum using the relations like this

$sum = Product::query()
           ->whereHas('post', function($post) {
               $post->whereHas('category', function($category) {
                   $category->whereHas('user', function($user) {
                       $user->where('id',auth()->id());
                   });
               });
           })
           ->sum('price');
N69S
  • 16,110
  • 3
  • 22
  • 36
  • 1
    I think you can also do `whereHas('post.category.user', function ($user) { $user->where('id', auth()->id()); })` – apokryfos Feb 18 '23 at 21:09