skip to Main Content

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!

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search