我可以在laravel雄辩的where子句中放入一个集合或数组吗?

时间:2018-08-10 19:59:03

标签: laravel collections eloquent laravel-query-builder

$collection=["c","a","f","h","j","o","k"]

$total_sums=Models::select('count')->whereIn('class',['c','a','f','h','j','o','k'])
                    ->get()
                    ->sum('count');

我可以这样使用变量$ collection吗?

$total_sums=Models::select('count')->whereIn('class',[''.$collection.''])
                    ->get()
                    ->sum('count');

2 个答案:

答案 0 :(得分:4)

您可以同时使用。

whereIn()接受ArrayCollection。 您只需将其作为第二个参数传递即可。

$array = ["c","a","f","h","j","o","k"];
$collection = collect($array);

$total_sums=Models::select('count')->whereIn('class', $array)
            ->get()
            ->sum('count');

// works

$total_sums=Models::select('count')->whereIn('class', $collection)
            ->get()
            ->sum('count');

// also works!

答案 1 :(得分:1)

否,因为$collection已经是一个数组。当您尝试将其连接为字符串时,我相信您的查询将如下所示...

select count from models where class in ('Array');

您可能真正想做的是...

->whereIn('class', $collection)