Grouping by region, aggregate function (grouping_error) column

Further Investigation
fragment("JSON_AGG(?)", e) instead of ("ARRAY_AGG(?)", e.id) would return you a Map with stringify keys.

I can’t somehow return the Schema within the fragment ?

Related articles:
It seems like other people have discussed this:
ecto-json-agg-for-structs
select-results-into-a-schema

Solution
Ben’s advice. Keep it simple. I did exactly what he suggested here is the solution:

    def group_by_region do
        results = 
            Location
            |> Repo.all
            |> Enum.group_by(fn(item) -> item.country_region end)

        keys =
            results |> Map.keys

        Enum.map(keys, fn(key) -> 
            %{}
            |> Map.put_new(:region, key)
            |> Map.put_new(:count, length(Map.get(results, key)))
            |> Map.put_new(:items, Map.get(results, key))  
        end)
    end
1 Like