按大小类别分组作为laravel php中的单独数组

时间:2017-10-13 07:47:35

标签: php laravel-5

我有表size_chart

| id | category | size | created_at          | updated_at | deleted_at |
+----+----------+------+---------------------+------------+------------+
|  1 | Regular  | S    | 2017-10-11 09:35:14 | NULL       | NULL       |
|  2 | Regular  | XS   | 2017-10-11 09:39:34 | NULL       | NULL       |
|  3 | Regular  | M    | 2017-10-11 09:39:37 | NULL       | NULL       |
|  4 | Regular  | xxl  | 2017-10-11 13:03:52 | NULL       | NULL       |
|  5 | Regular  | l    | 2017-10-11 13:03:59 | NULL       | NULL       |
|  6 | Regular  | xm   | 2017-10-11 13:04:03 | NULL       | NULL       |
|  7 | Small    | em   | 2017-10-11 13:05:04 | NULL       | NULL       |
|  8 | standard | em   | 2017-10-13 07:16:50 | NULL       | NULL       |

在此表中,我有一些示例数据。我需要根据类别对大小进行分组 For.eg

Regular = [s,xs,M,l,xm]
standard = [em]
small = [em]

如何在我的php控制器功能上实现这个功能

public function sizeFetch(Request $request){
        $cat_id = $request->id;
        $size_id = SizeCategory::where('category_id',$cat_id)->pluck('size_id');
    $size_details = SizeChart::whereIn('id',$size_id)->get();

        return $size_details;
    }

现在这个函数像这样返回

[
{
id: 1,
category: "Regular",
size: "S",
created_at: "2017-10-11 09:35:14",
updated_at: null,
deleted_at: null
},
{
id: 2,
category: "Regular",
size: "XS",
created_at: "2017-10-11 09:39:34",
updated_at: null,
deleted_at: null
},
{
id: 3,
category: "Regular",
size: "M",
created_at: "2017-10-11 09:39:37",
updated_at: null,
deleted_at: null
},
{
id: 7,
category: "Small",
size: "em",
created_at: "2017-10-11 13:05:04",
updated_at: null,
deleted_at: null
}
]

请帮我解决此问题

2 个答案:

答案 0 :(得分:2)

如果在获得结果后进行分组,可能会更容易。查询中的分组问题是它并没有真正按照您的期望进行。 (SQL中的GROUP BY可能应该被称为AGGREGATE BY

public function sizeFetch(Request $request){
    $cat_id = $request->id;
    $size_id = SizeCategory::where('category_id',$cat_id)->pluck('size_id');
    $size_details = SizeChart::whereIn('id',$size_id)
        ->get()->groupBy("category") //Group by category
             ->map(function ($group) {
                   return $group->pluck("size"); //Pluck size from each category member
             });

    return $size_details;
}

答案 1 :(得分:0)

GroupBy可以帮到你。 SizeCategory::where('category_id',$cat_id)->groupBy('size')->pluck('size_id');

了解更多information