CodeIn
CodeIn

Reputation: 31

Select and sum values in id laravel

I have a table that has user id values with innerjoin and points, I need to add these points.

$test = DB::table('users')
    ->orderBy('values.points', 'asc')
    ->join('values', 'values.id_user', '=', 'users.id_brother')
    ->get();

This displays:

user1 1
user1 1
user1 1

The value in Points needs to add up and display only once with the added points.

I need you to show:

User1 3

Upvotes: 0

Views: 1147

Answers (2)

amr degheidy
amr degheidy

Reputation: 317

you can use count method

look

https://laravel.com/docs/7.x/collections#method-count

Upvotes: 0

Ersoy
Ersoy

Reputation: 9604

you need to groupBy id_brother and sum points. I am not %100 about your table structure and columns

return DB::table('users')
    ->orderBy('total', 'asc')
    ->join('values', 'values.id_user', '=', 'users.id_brother')
    ->groupBy('users.id_brother')
    ->get([
        'users.id_brother',
        DB::raw('sum(values.points) as total')
    ]);

Upvotes: 1

Related Questions