sum data from multiple relation in multiple relation in laravel

48 Views Asked by At

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

1

There are 1 best solutions below

1
N69S On BEST ANSWER

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');