Laravel 4 where in condition with DB::select query
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19977291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4 where in condition with DB::select query
提问by Victor
I have next SQL query:
我有下一个 SQL 查询:
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.
我应该如何使用 Laravel 执行此操作?我将此查询放在 DB::select 函数中,但如何将所有 ID 置于“WHERE device_id IN (?)”条件中?我尝试使用“array(implode(',', $var))”,但它不起作用。如果我有像“13, 14”这样的 id,我只会得到 id = 13 的结果。
So the question is how to place instead of "?" array of ids?
所以问题是如何放置而不是“?” id数组?
采纳答案by Kasyx
Laravel is using PDO library. Sadly, binding with PDO doesn't work with WHERE IN
. You can read about it here.
Laravel 正在使用 PDO 库。遗憾的是,与 PDO 绑定不适用于WHERE IN
. 你可以在这里阅读它。
So what you have to do is to put prepared string in your query like this:
所以你要做的是把准备好的字符串放在你的查询中,如下所示:
"(...)
WHERE device_id IN (".array(implode(',', $var)).")
(...)"
回答by jszobody
Take a look at the docs here, scroll down to "Using Where In With An Array":
看看这里的文档,向下滚动到“使用数组中的位置”:
http://four.laravel.com/docs/queries
http://four.laravel.com/docs/queries
The whereIn
method takes an array, so pass in $var
directly, no need to implode.
该whereIn
方法需要一个数组,所以$var
直接传入,不需要内爆。
->whereIn('device_id', $var)
回答by vishal-mote
"(...)
WHERE device_id IN (".implode(',', $var).")
(...)"