Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 where in condition with DB::select query

Tags:

php

laravel

I have next SQL query:

SELECT summary_table.device_id, WEEKDAY(summary_table.day) as day, AVG(summary_table.shows) as avg_shows
    FROM (
         SELECT device_id, day, sum(shows) as shows
         FROM statistics
         GROUP BY device_id, day
    ) as summary_table
    WHERE device_id IN (1,2,3) // Just for example
    GROUP BY device_id, WEEKDAY(day)

How should I execute this using Laravel? I put this query in DB::select function, but how can I place all ids in "WHERE device_id IN (?)" condition? I tried using "array(implode(',', $var))" but it doesnt work. If I have ids like "13, 14" I get results only for id = 13.

So the question is how to place instead of "?" array of ids?

like image 255
Victor Avatar asked Oct 20 '25 07:10

Victor


2 Answers

Take a look at the docs here, scroll down to "Using Where In With An Array":

http://four.laravel.com/docs/queries

The whereIn method takes an array, so pass in $var directly, no need to implode.

->whereIn('device_id', $var)
like image 140
jszobody Avatar answered Oct 21 '25 22:10

jszobody


Laravel is using PDO library. Sadly, binding with PDO doesn't work with WHERE IN. You can read about it here.

So what you have to do is to put prepared string in your query like this:

"(...)
    WHERE device_id IN (".array(implode(',', $var)).")
    (...)"
like image 39
Kasyx Avatar answered Oct 21 '25 22:10

Kasyx