Get Count in mysql query in laravel - php

I wants to select the count of votes got for each items.Following query works fine but there is a problem if there is no vote for an item then that item is not showing in result.I actually wants details of each items and votes.If there is no vote for an item it should be shown count zero.
How can i achieve it?
DB::table('wonders')
->leftjoin('vote','votes.wonderId','=','wonders.id')
->select('wonders.id','wonders.title',DB::raw('count(votes.vote) as votes'))
->get();

Try this
DB::table('wonders')
->leftjoin('vote','votes.wonderId','=','wonders.id')
->select('wonders.id','wonders.title',DB::raw('ifnull(count(votes.vote),0) as votes'))
->groupBy('wonders.id')
->get();

maybe you need to use iffnull,try this
DB::table('wonders')
->leftjoin('vote','votes.wonderId','=','wonders.id')
->select('wonders.id','wonders.title',DB::raw('ifnull(count(votes.vote),0) as votes'))
->get();

Try this
DB::table('wonders')
->leftjoin('vote','votes.wonderId','=','wonders.id')
->selectRaw('wonders.id','wonders.title',count(votes.vote) as votes)
->groupBy('wonders.id')
->get();

Related

Getting the sum of columns in a Laravel raw select statement

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

How to achieve sub collection on a collection of an array?

I want to get the detailed product of a collection from groupBy in laravel. How can I achieve that?
I'm using php 7.1 and Laravel. I can get the collection for the total report for year, month, and day.
But can I get detailed product of that collection ?
My query for getting the collection in the controller
$totalBelanjaTahun = DB::table('assets')
->select(DB::raw('EXTRACT(MONTH FROM belitanggal_assets) AS monthCoba, SUM(beliharga_assets) AS harga_beli'))
->where('belitanggal_assets', 'like', '%'.$tahun.'%')
->groupBy(DB::raw('monthCoba'))
->get();
return view('DilarangBuka.reportTotalBelanjaTahun', compact('totalBelanjaTahun', 'tahun', 'totalPertahun'));
How can I achieve get detailed of product of that array, not just get the date and the price? Thanks
Don't groupBy records in mysql, you will get first record of every groups.
Try to get them out.
$totalBelanjaTahun = DB::table('assets')
->select(DB::raw('EXTRACT(MONTH FROM belitanggal_assets) AS monthCoba, beliharga_assets AS harga_beli, field1, field2, field3'))
->where('belitanggal_assets', 'like', '%'.$tahun.'%')
->get();
And groups them by collect
collect($totalBelanjaTahun)->groupBy('monthCoba')
Hope this can help you.

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')

Prevent getting a duppicate data from the database in CodeIgniter

I'm trying to get data from the database filtered by some categories
This is my code in CodeIgniter
$this->db
->select('*')
->from($this->table)
->join('sites','sites.id = categories_by_site.site_id')
->where('categories_by_site.category_id', $categories[0])
->or_where('categories_by_site.category_id', $categories[1])
->order_by('id', 'ASC')
->get()
->result();
I simplify my code for the sake of this question, the above query take the categories as a search filter and used it to get result from the database.
There can be many categories filter to search at the same time, that's why I am using or_where() method.
The problem with this, when I got the result data, it has duplicate row of entries in object array.
Anyone can suggest how to prevent from getting a duppicate data from the database using above query?
Thanks
You can use group_by to solve this issue
Replace your code with
$this->db
->select('*')
->from($this->table)
->join('sites','sites.id = categories_by_site.site_id')
->where('categories_by_site.category_id', $categories[0])
->or_where('categories_by_site.category_id', $categories[1])
->order_by('id', 'ASC')
->group_by('categories_by_site.category_id')
->get()
->result();
You can eleminate duplicate values using distinct or group by
As you select all fields a group by is better in my opinion. Example to group by category_id
$this->db->group_by('category_id');

laravel query php how to get max value within a range

hello how do i get the max value of scores, where column ID range starts at 3-5
example table
I want to get the max value of scores, where column ID ranging from 3-5
, please help,
what I have done so far:
$max_scores_table= DB::table('scores_table')
->where('id', '>', 2)
->max('score');
another problem is when i have a decimal points in the table
when I used the max() function it gets the ID=5, which has a Score of 4.5, instead of ID=4 with a value of 4.6, tnx in advance
Try to use whereBetween hope this works:
$max_scores_table= DB::table('scores_table')
->select(DB::raw('MAX(score) FROM scores_table as MaxScore'))
->whereBetween('id', array(3,5))
->where('score', 'MaxScore')
->get();
OR:
$max_scores_table= DB::table('scores_table')
->whereBetween('id', array(3,5))
->max('score')
->get();
Write query as below:
$max_scores_table = DB::table('scores_table')
->whereBetween('id',array(3,5))
->max('score');
Reference: Laravel API
Use query like this
$max_scores_table = DB::table('scores_table')
->whereBetween('id', array(3, 5))->max('score')->get();
For your reference just follow Laravel Documentation

Categories