Return struct while doing group_by

I am trying to get data in this form

      "12" => [
          "id" => "1",
          "inserted_at" => "2021-10-25T16:06:14.318722"
           ..... rest of the field

I have a query to get the data in that form but I am not able to return the Job struct.

from(job in subquery(query), group_by: job.user_id, select: %{job.user_id => fragment("array_agg(json_build_object('id', ? , 'inserted_at', ?))",, job.inserted_at)})

This approach is working but I have to add all the fields from the Job struct. Any idea how i will be able to return the whole Job struct ??

1 Like

Can’t write a better Ecto query off the top of my head but an alternative solution is to just get all the records from Ecto via a normal query and then pipe it to Enum.group_by.

1 Like