Make consultation with distinct in Laravel

Asked

Viewed 3,486 times

0

I have the following table:

inserir a descrição da imagem aqui

I need to count the amount of records where the supplier_id is equal to 2 but without repeating the column order_id. In this case it would return 1, since it has two records with 2 na supplier_id, but order_id is 1 in both records

I used the query below in mysql and returned correctly 1 record:

SELECT COUNT(DISTINCT order_id) FROM timelines WHERE supplier_id = 2;

I used the query below in Laravel and returned me 2 records

DB::table('timelines')
    ->where('supplier_id', 2)
    ->groupBy('order_id')
    ->count(); 

How could I return the correct amount which in case is 1 record?

1 answer

2


Use the selectRaw in queryBuilder

$db = \DB::table('timelines')
       ->selectRaw('COUNT(DISTINCT order_id) AS total')
       ->where('supplier_id', 2)
       ->first();

var_dump($db->total);

But be careful when using, this is vulnerable to SQL Injection attacks.

The way you did, when you debug the code, you get the query

select count(*) as aggregate from `timelines` where `supplier_id` = 2 group by `order_id`;

Despite the GROUP BY return only one element, the count(*) will count all records, regardless of the GROUP BY.

If you do not want to use selectRaw, you can use this way:

$db = \DB::table('timelines')
    ->select('order_id')
    ->where('supplier_id', 2)
    ->groupBy('order_id')
    ->get(); 

var_dump( count($db) );
  • Wasn’t groupBy supposed to work? It’s like no selectRaw?

  • I edited my reply, add the answers to these other questions.

  • The two forms you passed worked. The second form generates an error: sql_mode=only_full_group_by. I set false in config/database.php and the error is gone. Do you have a problem with Strict? It would be possible to do the second way without disabling this Strict mode?

  • It is possible yes, this error is because you are using a field in the group by, but is not selecting that same field in select. To fix this just add ->select('order_id') in Query Builder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.