How to modify nested Laravel collection using group by

Viewed 38

I want to modify nested collection using group by.

This is sample collection

    "document": [
        {
            "id": 1,
            "company_id": 4,
            "client_id": 1,
            "status": 1,
            "client": {
                "id": 1,
                "company_id": 4,
                "name": "1663159185735-client"
            },
           "document_items": [
                {
                    "id": 1,
                    "master_id": 5,
                    "text_value": "piyo",
                },
                {
                    "id": 2,
                    "master_id": 5,
                    "text_value": "fuga",
                },
                {
                    "id": 3,
                    "master_id": 3,
                    "text_value": "hoge",
                }
            ]
        }
    ]

I want to change like this.

    "document": [
        {
            "id": 1,
            "company_id": 4,
            "client_id": 1,
            "status": 1,
            "client": {
                "id": 1,
                "company_id": 4,
                "name": "1663159185735-client"
            },
           "document_items": [
                5: [{
                    "id": 1,
                    "master_id": 5,
                    "text_value": "piyo",
                   },
                   {
                    "id": 2,
                    "master_id": 5,
                    "text_value": "fuga",
                   }
                ],
                3: [{
                    "id": 2,
                    "master_id": 5,
                    "text_value": "fuga",
                       }
                  ]
            ]
        }
    ]

I try write below code;

        $result->map(function ($v){
            
            $v->documentItems = $v->documentItems->groupBy('master_id');
            return  $v;
        });

but output key is documentItems not document_items

I changed to

 $v->document_items = $v->documentItems->groupBy('master_id');

key is drawing_drawing_items but not groupby(simple array)

how to modify group by and preserve key case?

1 Answers
I changed to

 $v->document_items = $v->documentItems->groupBy('master_id');
key is drawing_drawing_items but not groupby(simple array)

You should also change like this $v->document_items->groupBy('master_id')

The key is 'document_items' not 'documentItems'

Related