在laravel中的Groupby将对象中的项目分组

时间:2018-01-21 19:33:32

标签: php laravel group-by

是的,不确定我做错了什么或者Laravel中的Illuminate \ Database是个问题

我的代码:

            $sth = Insect::leftJoin('types', 'types.id', '=', 'families.type_id')
                        ->select('types.name as types','families.id','families.name')
                        ->get()
                        ->groupBy('types');

groupBy之前的结果是:

[
{
    "types": "moths",
    "id": 1,
    "name": "Bombycidae"
},
{
    "types": "moths",
    "id": 2,
    "name": "Brahmaeidae"
},
{
    "types": "moths",
    "id": 3,
    "name": "Cossidae"
},
{
    "types": "larvas",
    "id": 6,
    "name": "test"
}]

但是使用GroupBy:

{
"moths": [
    {
        "types": "moths",
        "id": 1,
        "name": "Bombycidae"
    },
    {
        "types": "moths",
        "id": 2,
        "name": "Brahmaeidae"
    },
    {
        "types": "moths",
        "id": 3,
        "name": "Cossidae"
    }
],
"larvas": [
    {
        "types": "larvas",
        "id": 6,
        "name": "test"
    }
]

}

所以我的问题是,我想摆脱对象中的那些类型......

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

好的,首先你正在做的是在结果集合上调用groupBy,这与GROUP BY MySQL查询子句无关,后者命名非常严重(不相关,但值得注意) )。

您可以将结果映射到您需要的地方:

 $sth = Insect::leftJoin('types', 'types.id', '=', 'families.type_id')
                    ->select('types.name as types','families.id','families.name')
                    ->get()
                    ->groupBy('types')->map(function ($group) {
                          return $group->map(function ($value) {
                                return [ "id" => $value->id, "name" => $value->name ];
                          });
                     });

答案 1 :(得分:0)

您可以删除选择类型,而是执行以下操作:

$sth = Insect::leftJoin('types', 'types.id', '=', 'families.family_id')
    ->select('families.id','families.name')
    ->groupBy('insects.id', 'types.name')
    ->get();

另外,要查看原始查询的实际操作,您可以使用以下

$sth = Insect::leftJoin('types', 'types.id', '=', 'families.family_id')
    ->select('families.id','families.name')
    ->groupBy('insects.id', 'types.name')
    ->toSql();

dd($sth);

您正在选择要在对象中使用的collumns,因此如果您从select语句中删除它,它将不再显示在您的对象中,您还可以将类型添加到类型模型中的$hidden输入像这样:

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'name',
];

在laravel中分组:https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset

隐藏数组中的行:https://laravel.com/docs/5.5/eloquent-serialization#hiding-attributes-from-json