Getting the sum of columns in a Laravel raw select statement - php

I am trying to get the sum of the records that are returned in a Laravel select statement but I can't seem to get it right.
My original statement is as follows;
$results = DB::table('polls')->select('polls.id as poll_id', 'poll_votes.vote_count as vote_count', 'poll_options.id as poll_option_id')
->join('poll_options','polls.id','=','poll_options.poll_id')
->join('poll_votes', 'poll_options.id', '=', 'poll_votes.poll_option_id')
->where([['polls.status','=','1'], ['poll_options.status','=','1'],])
->get();
I have tried adding the following after the last element on the ->select line but I keep getting errors;
DB::raw('sum(poll_votes.vote_count) total_votes')
Any help would be greatly appreciated

To fix the error you are receiving, use the groupBy before your ->get method:
->groupBy('polls.id');

You want the sum of Colum or Count all the records: https://laravel.com/docs/5.8/queries#aggregates

Related

Laravel Eloquent Where not working after joining table

Hi I have written a little query which doesnt seem to working when I use Eloquent but works when I write something similar in MySQL. Data isnt being retuned which shouldnt be due to my where clauses.
I have written this query which isnt working as expected -
$invoices = Invoice::leftJoin('user_details', 'invoices.user_id', 'user_details.user_id')
->where('invoices.practice_id', '!=', 'user_details.practice_id')
->first();
It is returning data where the invoice.practice_id = user_details.practice_id
I altered the query to prove it isnt working -
$invoices = Invoice::select('invoices.practice_id', 'user_details.practice_id')
->leftJoin('user_details', 'invoices.user_id', 'user_details.user_id')
->where('invoices.practice_id', '!=', 'user_details.practice_id')
->first();
The values returned the practice_id is 6, 6 which shouldnt be possible due to the following where clause where('invoices.practice_id', '!=', 'user_details.practice_id')
Have I done something wrong which I am just not seeing?
Thank you for any help you can provide!
UPDATE
Here is the DB schema for the invoice table
Here is the the DB schema fro the user_details table
The expected result is mentioned above, no results should be returned if invoice_practice_id = user_details.practice_id
#Luke Rayner
Try by rewriting line ->leftJoin('user_details', 'invoices.user_id', 'user_details.user_id')
to
->leftJoin('user_details', 'invoices.user_id', '=', 'user_details.user_id')
If not try to print Last query and post it

Laravel Query Buider Group By Not Getting All The Records

I am trying to get the data using groupBy on type field from my transaction table. I am using this query
DB::table($this->table)
->select()
->whereRaw($where['rawQuery'], isset($where['bindParams']) ? $where['bindParams'] : array())
->groupBy('type')
->get();
But it is not giving the complete records. There are more than 10 records in my table. But it is giving me only two. One for type=1 and another for type=2. It is selecting only on record from each type. I am expecting that i will get all the transactions based on condition grouped in two result set. Anyone know why it is happening?
Try to call Collection groupBy instead. Just put groupBy after get(). It should work.
DB::table($this->table)
->select()
->whereRaw($where['rawQuery'], isset($where['bindParams']) ? $where['bindParams'] : array())
->get()
->groupBy('type');
Faq::where('type','host')->get()->groupBy('category');

how to group by in db query builder to get the unique value?

Can someone help me to convert the below mysql to laravel db query builder or eloquent?Here is my mysql
SELECT max(created_at), jobseeker_id,call_reason,type_of_call
FROM calllogs
GROUP BY jobseeker_id
ORDER BY created_at DESC;
Here is my tries, but no luck yet.
$jobseekers =DB::table('calllogs')
->select(DB::raw("max('created_at'),jobseeker_id"))
->groupBy('jobseeker_id')
->orderBy('created_at','desc')
->get();
dd($jobseekers);
Please help me out.
$jobseekers =DB::table('calllogs')
->select(DB::raw("max(created_at),jobseeker_id"))
->groupBy('jobseeker_id')
->orderBy('created_at','desc')
->get();
Try with this code.
Only delete ' ' in max.
It will work well.
DB::table(calllogs)
->select(DB::raw('max(created_at) as max_created_at'),
'jobseeker_id','call_reason','type_of_call')
->groupBy('jobseeker_id')
->orderBy('max_created_at', 'DESC')
->get(); =>As a array.
->first(); => As a object.
Additionally, If you are using table joins see below.
->join('table_1','table_1.id','=','table_2.table_1_id')
->leftjoin('table_1','table_1.id','=','table_2.table_1_id')
->rightjoin('table_1','table_1.id','=','table_2.table_1_id')
ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'myapp.calllogs.created_at'
Two solution for that error
1.In config/database.php file make sql strict mode to false.
(or)
2. IN groupBy Clause add all your table colums.
example:
->groupBy('jobseeker_id','jobseeker_name','jobseeker_email')

Nested Query in Laravel 5.2 Query Builder Pulling MAX date

I'm trying to pulling a group of users who have not made a transaction since a specified date.
This is my query:
$notActive = DB::table('transactions')
->join('users','transaction.user_id', '=', 'users.user_id' )
->select(DB::raw('users.user_id, users.name, max(transaction.last_posted_date) AS lastDate'))
->groupBy('users.user_id')
->where('lastDate', '<', ''.$not.'');
return Datatables::of($notActive)
->make(true);
$not is the date value pulled in. This produces an ajax data-tables error. I've tried this multiple ways including putting a select statement for the max date in the where clause but it keeps throwing up errors. Is there a better way to query this data that I want? Thanks.
I figured it out! Using the having clause brought up those users who had transactions with dates less than the date that was being provided by the input field (i.e. Not Active Since)
$notActive = DB::table('transactions')
->join('users','transactions.user_id', '=', 'users.user_id' )
->select(DB::raw('users.user_id, users._name, max(transactions.last_posted_date) as last_posted_date'))
->groupBy('users.user_id')
->having('transactions.last_posted_date', '<', ''.$not.')');
return Datatables::of($latestTransactions)
->make(true);

Laravel 5.1 Eloquent whereBetween not working as expected

I have to get rows within a range of passed symbol no.
Image of Table from where query is to be done
Query:
Mark::select('users_id', 'symbol_no', 'mark_obtained')
->where('subject_trade_id', 2)
->whereBetween('symbol_no', [100, 1000])
->orderBy('symbol_no')
->get();
This query returns no data, but I was expecting total 9 rows form the query.
If I dump the query, I find the query as expected.
Query Log Image
If I run the generated query to mysql then it woks fine.
Again, if I change the symbol no. range to something like this:
Mark::select('users_id', 'symbol_no', 'mark_obtained')
->where('subject_trade_id', 2)
->whereBetween('symbol_no', [10, 1011])
->orderBy('symbol_no')
->get();
It returns 2 rows this time, and this output is also wrong.
If I try changing symbol no. range and query like this:
Mark::select('users_id', 'symbol_no', 'mark_obtained')
->where('subject_trade_id', 2)
->whereBetween('symbol_no', [101, 200])
->orderBy('symbol_no')
->get();
Now it works fine as expected.
Found the problem
By mistake the symbol_no column was defined as varchar() which had to be int() so, whereBetween() was being unable to return expected data.
I faced same problem.. Could you please check "symbol_no" field type in database table, It should be number/integer.

Categories