laravel collect函数未定义

时间:2018-03-14 11:09:07

标签: php laravel

我从数据库中获取需要分组的数据,所以我将数据库结果集转换为数组,然后将其传递给laravel collect helper但我给了我错误

#Create the data.table
dt <- data.table(c(1:10))
#Create a keep column which is set to 1 for those which respect condition and 0 for the others
dt[,keep:=ifelse(V1>3&V1<7,min(V1),0)][]
#Then create sig column which contains only the value you want to keep 
dt[,sig:=ifelse(keep==0,0,V1*keep)][]
#And finally, you want to store only the first value which respect the condition, so if your data frame is order by number, you can take the min value by V1 column.
dt[,sig:=min(sig),by=keep][]

代码

dt[,c(1,3)]
    V1 sig
 1:  1   0
 2:  2   0
 3:  3   0
 4:  4   4
 5:  5   4
 6:  6   4
 7:  7   0
 8:  8   0
 9:  9   0
10: 10   0

请帮助我解决我的错误,我想使用laravel collections方法groupby将数据库结果数组分组为&#34; age_group&#34;

account_id

下面的数据组
Call to undefined function collect()

3 个答案:

答案 0 :(得分:2)

您不需要添加收集功能,因为您已经收集了一个集合。所以你需要这样做:

$user_profile = UserProfileItem::where('type', "age_group")->get()->groupBy("age_group");

答案 1 :(得分:1)

您需要首先获取组并循环遍历它们并将数据添加到集合

$groups = UserProfileItem::groupBy("age_group")->get();
$collection = collect();

foreach($groups as $group){
  $data = UserProfileItem::where('type', $group->type)->get();

  $collection->put($group->type , $data);
}

return $collection;

答案 2 :(得分:0)

我认为对于以前版本的laravel创建自己的组是唯一的解决方案

   public function getGroupedUser($group="age_group"){

        $users = $this->users->keyBy('id')->toArray();
        $user_profile=UserProfileItem::where('type', "age_group")->get()->groupBy("age_group");
        foreach ($user_profile as $row){
            $urow[$row['data']][]=$row;
        }
    echo "<pre>";
        print_r($user_profile);die;
    }