Monday, March 13, 2017

Laravel query getting count(*) instead of distinct id

I'm really stumped on this. I'm using Laravel 4.2 to develop a web application in PHP, and I keep getting messed up results on our contacts page. Basically, the first step in this feature is to get a filtered list of contacts starting with a list of contact ids (with some additional criteria in the query for which contacts to select) and manipulate the list later on in my code. I believe there is an issue with that query that is messing things up later on, and I'm not sure why. So, here is my query, pared down to just the part of the query to get all the contact ids, rather than ones that meet a criteria:

$contacts = DB::table('contacts')
    ->select(DB::raw('distinct contacts.id'))
    //other filtering criteria that doesn't seem to be the source of the problem
    ->whereRaw('contacts.id in (' . $contact_ids_string . ') ');

where $contact_ids_string is a string I built earlier in the code containing the contact ids (I kept getting weird errors trying to bind $contact_ids to the query, so I just did it this way.

Anyway, I keep getting weird results, so I introduced a typo into the query to get an error message so I could look at the query that was being built, and here is the query (with the typo removed):

select count(*) as aggregate from 'contacts' where contacts.id in (1, 2, 3, 4, 5, 6)

I think the problem might be that the query contains count(*) rather than distinct contacts.id, which is what I want.

Any ideas why this is happening, and how to resolve it? Thanks!



via AWeston

Advertisement