0

I am trying to get sum of amount of all users group by month.But if I add sum then query not work.It return amount log as blank array But without sum query return all logs data as monthly.

My query

$reports = $user->whereHas('groups', function ($query) use($acceptedGroup) {
    $query->whereIn('groups.name',$acceptedGroup);
})->with(
    array(
        'amountLogs' => function($query) use($year){
            $query
            ->select(
                DB::raw('sum(amount) as total')
            )
                ->whereYear('created_at','=',  $year)
                ->groupBy(DB::raw("MONTH(created_at)",'user_id'))->get();
        })
);

If I remove

            ->select(
                DB::raw('sum(amount) as total')
            )

Then query works

1
  • What version of laravel are you on? Try selectRaw instead of select Commented Sep 30, 2018 at 22:21

1 Answer 1

2

If you creating a specific select on a relationship in your query, you also need to include the foreign key to the related table (in your case, probably the users table)

->select(
   'user_id',
    DB::raw('sum(amount) as total')
)

This allows Eloquent to relate the records after loading from the database.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.