1

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!

1
  • I have tried your code. It works fine. Did your model connect the right database or define the right table name? Commented Nov 4, 2019 at 3:33

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank for your answer sir, i have copy+paste the sintax, but still not working,, hmm
0

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

2 Comments

my sintax isn't resulting any error, but only show 'nothing' idk whyy :(
if you change the column name workcenter to workcente2r for example that should have result to a column not found error and will output your query with the wrong column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.