Ukieweb

Diary

I write what I learn here

Aggregate Functions In Laravel SQL

Aggregate Functions In Laravel SQL

Task: Get all users and their contribution total. Every contribution is stored as a row in _contributions _table. Tables:

  1. Contributions- stores user contributions
  2. Users- stores user details

Query: $contributions= DB::table('contributions') ->leftJoin('users', 'users.id', '=', 'contributions.user_id') ->select(DB::raw('SUM(amount) as balance'),'name', 'user_id', 'created_by', 'contribution_date', 'year', 'contributions.created_at', 'status', 'users.id') ->orderBy('name','desc') ->groupBy('user_id') ->get();

return $contributions;

This query returns the fields in the select function with the aggregated total amount with an alias name 'balance'

0 Comments

To make a comment you have to login