-1

Hello I am very new to Laravel and am having a big problem converting the following MYSQL query into a Laravel Query Builder. I am using Laravel 5.2.

Here is the working MYSQL query:

select * from
(select b.id, SUM(v.value) as total
from blog_entries as b
ON v.votable_id = b.id AND v.votable_type = 'App\\BlogEntry'
LEFT JOIN votes as v
GROUP BY b.id
ORDER BY total desc)
AS Data where Data.total > 0;

Is it possible to utilise Eloquent to execute this query? I have read through Laravels Query Builder Documentation and it has gone way over my head. Any help or pointers would be greatly appreciated.

Thanks for your time and help!

GustavMahler
  • 657
  • 1
  • 6
  • 23

1 Answers1

0

I have found an solution to translating the SQL into Laravel Query Builder form:

Working Using Laravel's Query Builder:

DB::table('blog_entries')
  ->select('blog_entries.id', DB::raw('SUM(votes.value) as total'))
  ->leftjoin('votes', function ($join) {
          $join->on('votes.votable_id', '=', 'blog_entries.id')
               ->where('votes.votable_type', '=', 'App\BlogEntry');
  })
  ->groupBy('blog_entries.id')
  ->having('total', '>', 0)
  ->orderBy('total', 'DESC')
  ->get();
Community
  • 1
  • 1
GustavMahler
  • 657
  • 1
  • 6
  • 23