Home > Software engineering >  Laravel query builder group into nested arrays
Laravel query builder group into nested arrays

Time:03-14

I am using Laravel with query builder in my project.

I have the following table:

Table: worker_tasks
 -------- ----------- ------------ --------------------- 
| id     | worker_id | task_id    | started_at          |
 -------- ----------- ------------ --------------------- 
| 227350 |     50765 |       2399 | 2021-12-02 12:24:38 |
| 227351 |     50765 |       1377 | 2021-12-12 09:34:22 |
| 227352 |     84245 |       2294 | 2021-12-07 10:37:11 |
 -------- ----------- ------------ --------------------- 

And I wish to retrieve data into an array of nested arrays, with worker_id as key of each one.
In this case, expected result will be:

[
    50765 => [
        {
          "task_id": 2399,
          "started_at": "2021-12-02 12:24:38",
        },
        {
          "task_id": 1377,
          "started_at": "2021-12-12 09:34:22",
        },
    ],
    84245 => [
        {
          "task_id": 2294,
          "started_at": "2021-12-07 10:37:11",
        },
    ],
]

I tried to use the keyBy collection method, but it takes only one element for each key, as written in documentation:

If multiple items have the same key, only the last one will appear in the new collection

I wonder whether there is a straight way to do it (using some built-in Laravel method).

CodePudding user response:

Use the GroupBy method instead of keyBy

  • Related