Laravel Eloquent Model use select count(column) - php

I just want to use the following raw DB query with Laravel Eloquent model.
SELECT
<column_name>,
COUNT(<column_name>) AS `value_occurrence`
FROM
<my_table>
GROUP BY
<column_name>
ORDER BY
`value_occurrence` DESC
LIMIT 1;
Let's say I have a model called TestModel. I just would like to do something like the following.
TestModel::select('column_name', 'COUNT(column_name) AS occurrences')
->groupBy('column_name')
->orderBy('occurences')
->limit(10)
->get();
Can you help me please? Thanks...

I just found out that I can use selectRaw to use Count(column_name) in the code however, if there is any better way of doing it, I would like to see it.
Thanks...
The answer:
TestModel::selectRaw('column_name, COUNT(column_name) AS occurrences')
->groupBy('column_name')
->orderBy('occurences')
->limit(10)
->get();

Related

How to convert this MySQL query to Laravel?

Here my MySQL query (work in phpMyAdmin) :
SELECT workcenter, (SUM(w1+w2 +w3 +w4)/ (COUNT(DISTINCT(teknisi))*40*4) )*100 AS total FROM `team` GROUP by workcenter ORDER BY total
then, i try in Laravel Sintax like this below (not work) :
$sql = Team::groupBy('workcenter')->select('workcenter', \DB::raw('(SUM(w1+w2+w3+w4)/ (COUNT(DISTINCT(teknisi))*30*4) )*100 AS total'))
->OrderBy('total', 'Desc')
->get();
When i run the laravel sintax, its doesn't show any errors, but the output is nothing..
Please anyone help me to convert the MySQL query to Laravel Sintax. Thank you!
I think you are close enough, however, this doesn't look like a correct way to group by with Eloquent ORM. Try using raw expressions, something like this might work:
$sql = DB::table('team')
->select(DB::raw('workcenter, (SUM(w1+w2 +w3 +w4)/ (COUNT(DISTINCT(teknisi))*40*4) )*100 as total'))
->orderBy('total', 'desc')
->groupBy('workcenter')
->get();
More about raw expressions here - https://laravel.com/docs/6.x/queries#raw-expressions
Whenever I want to convert SQL query to Laravel I always change one column name, the laravel error report will show your current query and u can compare it to the SQL query

Change MySQL select round query to Laravel 5.5

How to change this query to Laravel 5.5
"SELECT ROUND((COUNT(STATUS)/(SELECT COUNT(*) FROM data_ap))*100,1)
FROM data_ap WHERE STATUS LIKE '%UP%'";
Something like that :
\DB::table('data_ap')
->select(\DB::raw('ROUND((COUNT(STATUS)/(SELECT COUNT(*) FROM data_ap))*100,1) as calc'))
->where('STATUS','like','%UP%')
->get();
I think you must keep native query with Raw Expressions, for more here https://laravel.com/docs/5.6/queries#raw-expressions
#Muhammad Anwari: You can simply point the targeted column/alias
\DB::table('data_ap')
->select(\DB::raw('ROUND((COUNT(STATUS)/(SELECT COUNT(*) FROM data_ap))*100,1) as calc'))
->where('STATUS','like','%UP%')
->first()->calc;

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

laravel query builder

I want to write sql query
SELECT
*,
SUM(item_quantity)
FROM sales
GROUP BY item_id
ORDER BY SUM(item_quantity) DESC LIMIT 5
On laravel query builder but failed.
Can anyone please help me.
I use Model() instead of DB.
I think you are looking the following solution:
$sales = Sales::select('*', 'SUM(item_quantity) as total_item_qnty')
->groupBy('item_id')
->orderBy('total_item_qnty', 'desc')
->take(5)
Try this code

Get date from timestamp in laravel

How can I get date from "2015-07-31 06:03:21" using Laravel query builder?
In normal query using DATE() we can get date easily, but I don't know how to use DATE() in Laravel query builder. Please check my code sample given below and correct me?
Normal Query
SELECT DATE('2015-07-31 06:03:21'), customer_id FROM customer_histories
Laravel Query Builder
$customerhistory = Customerhistory::where('customer_id', 1)
->select('freetext', 'DATE(created_at)')
->get();
You can do this with DB::raw(), though if you are only selecting it, why not just take created_at complete? By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon so you can handle it like this in your code:
$customerhistory = Customerhistory::where('customer_id', 1)
->select('freetext', 'created_at')
->get();
dd($customerhistory[0]->created_at->toDateString());
You can use DB::raw('something') for that. In this case your raw input will be treated as part of actual SQL.
This is something you might wanna give a try:
$customerhistory = Customerhistory::where('customer_id', 1)
->select('freetext', DB::raw('DATE(`created_at`)'))
->get();
More details and yet another example cal be found here.
Also it looks like you're using eloquent. You might wanna check the mutators section.
$customerhistory = Customerhistory::where('customer_id', '=', '1')
->select('freetext', DB::raw('DATE(`created_at`)'))
->get();
Thanks.

Categories