laravel query builder - php

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

Related

Laravel Eloquent Model use select count(column)

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();

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

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

Add custom field during select mysql in laravel query

I have this query in laravel 5.2
$obj_custom_stdy_data = QstCustomStudyData::where('student_id', $this->data_user['student_id'])
->select($list_id . ' as list_id ', 'chapter_id', 'subject_id', 'subject_code_id')
->get()
->toArray();
Well I have a fixed value $list_id got from top code. Actually I want to add new field during query selection as list_id. However I got error for such that method.
When I tried in mysql IDE for example:
SELECT (1+2) as total, c.* FROM users
Then the result is no wrong at all.
Is that anyway to write in query builder for laravel instead of raw style?
You can take the use of DB::raw() method of QueryBuilder like this:
->select(DB::raw('(1+2) as total'));
See more about Query Builder's Raw Expressions
Hope this helps!

Empty where clause in Laravel 5.1 preferring eloquent method

i am looking to produce the following query in laravel 5.1 with eloquent method.
The mysql query is a follows
SELECT * FROM orders WHERE 1 = 1 ORDER BY o_date DESC LIMIT 25
No matter what i cant get the
WHERE 1 = 1
part working.
am new to laravel and pretty sure this is easy. but can't figure it out.
I have tried the following variations
$orders = orders::where('1', 1)->orderBy('o_date', 'desc')->take(25)->get();
$orders = orders::where(1)->orderBy('o_date', 'desc')->take(25)->get();
$orders = orders::where('1', '=', '1')->orderBy('o_date', 'desc')->take(25)->get();
but its not working. the query results is as shown below
> select count(*) as aggregate from `orders`
Seems like (looking at 1=1) you need whereRaw
$orders = orders::whereRaw("any clause u wish")->orderBy('o_date', 'desc')->take(25)->get();
but if "any clause u wish" is not a VERY-VERY dinamical part u'd better look what else you can use
http://laravel.com/api/5.0/Illuminate/Database/Query/Builder.html
For the above example the below code works fine
$orders = orders::whereRaw("1 = 1")->orderBy('o_date', 'desc')->take(25)->get();
Why do you want to create a condition that will be always true? I think that Eloquent is smart enought to remove this useless part of the query.

Categories