0

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).

1 Answer 1

2

Use the GroupBy method instead of keyBy

Sign up to request clarification or add additional context in comments.

1 Comment

Just to make it clear, the call to groupBy() must be done after the get() call: $query->get()->groupBy(['worker_id']).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.