mrobbizulfikar
mrobbizulfikar

Reputation: 461

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!

Upvotes: 1

Views: 112

Answers (2)

idirsun
idirsun

Reputation: 604

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

Upvotes: 0

Victor Lava
Victor Lava

Reputation: 121

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

Upvotes: 1

Related Questions