DuyDuc94
How to select_merge with fragment?
I have a list like this
selected_fields = [:inbox_count, :phone_number_count, :comment_count, ...] #this list contains fields of a table, and can change by the needed
group_query =
from(
ps in PageStatistic,
where: ps.id in ['1', '2']
group_by: fragment("date(?)", ps.hour)
select: %{
day: fragment("date(?)", ps.hour),
}
final_query =
select_fields
|> Enum.reduce(group_query, fn field, query ->
field_string = to_string(field)
select_merge(query, [ps], %{^field_string => fragment("sum(?)", field(ps, ^field))})
)
Repo.all(final_query)
but i got result like this
[
%{
:day => ~D[2023-01-01],
"inbox_count" => 3,
...
},
...
]
Is there any way make key “inbox_count” is an atom same as :day when query(i don’t want to loop the result to convert string to atom)
And is there any solution to select sum all fields that exist in select_fields when i make a query to database
P/s: i’m using Ecto v3.0
Most Liked
fuelen
Upgrade to the latest version of ecto and use ^field instead of ^field_string.
I created the issue on Github Unable to set keys dynamically using select_merge · Issue #4326 · elixir-ecto/ecto · GitHub
And it was resolved in this PR Don't send dynamic map keys to the database by greg-rychlewski · Pull Request #4327 · elixir-ecto/ecto · GitHub
sodapopcan
That sounds more like the value of the field you are trying to select into is the wrong type, although you are returning a bare map so that shouldn’t matter ![]()
I am, however, realizing that I mistakingly read Ecto 3.0 as 3.10, so that likely has something to do with it because I can’t for the life of me reproduce this in 3.11. Very sorry about that
![]()







