jc1992
jc1992

Reputation: 644

How to sum groupBy in Laravel5

Is a simple question about Eloquent , this eloquents returns correctly the user group by name

$pujas = Bid::orderBy('created_at','desc')->take(10)->usuarios()->subasta()->groupBy('id_user')->get();

I need to sum the value of the users import in the auction, the row is called 'importe', the result now with this eloquent is this :

enter image description here

UPDATE QUESTION

I managed to get the sum of the id_subasta , how could I pass two variable with return response()->json ?

$pujas = Puja::take(10)->usuarios()->subasta()->orderBy('created_at','desc')->get();
        $result = DB::select('SELECT SUM(importe) FROM pujas WHERE id_subasta = 15');
        if(\Request::ajax()) { 
            return response()->json($pujas);
                  }else{
            $mensaje = "NO";
        }

Upvotes: 2

Views: 407

Answers (1)

Bouhnosaure
Bouhnosaure

Reputation: 78

i think you must use the drilldown approach and use the sum function of the query builder.

$pujas = Bid::take(10)->usuarios()->subasta()->groupBy('id_user')->orderBy('created_at','desc')->get();

and for sum values you can create a service or loop over the users and sum the "imports" or add a new accessor in you model (in order to add a virtual attribute ) for getting the sum for one user.

Upvotes: 1

Related Questions