Mysql query to Query Builder

50 Views Asked by At

I want to take this SQL query to a query in Laravel Query Builder. It is important that the result be of type Query Builder. Please if you can help me.

SELECT MAX(sub.total) as total, sub.vendedor
FROM
(
    SELECT COUNT(id) as total, vendedor  
    FROM data_reports dr
    GROUP BY vendedor
) sub

I have the following but I couldn't go any further.

$data = DB::table('data_reports')
    ->select(DB::raw('COUNT(id) as total, vendedor'))
    ->groupBy('vendedor');
1

There are 1 best solutions below

1
arya_la On BEST ANSWER

Here is the query:

$results = DataReport::select(DB::raw('MAX(sub.total) as total, sub.vendedor'))
->from(function ($query) {
    $query->select(DB::raw('COUNT(id) as total, vendedor'))
        ->from('data_reports')
        ->groupBy('vendedor');
}, 'sub')
->get();