Ecto exception that reports is not a valid query expression

I have query, where I have to select a value that goes like this

select: %{ sum_total: sum(m.quantity * m.price * m.factor)}

Where m is table from a join clause and I would like to order by the sum_total key. The problem is that above query raise an exception that basically tells me that is not a valid query expression.

2 Likes

Can you post the whole query?

2 Likes

You can do it with a fragment. This might not be the exact syntax (my UI is slower than even normal right now), but something like:

select: %{sum_total: fragment("sum(? * ? * ?)", m.quantity, m.price, m.factor)}

The reason why you need a fragment is that ecto does not recurse down into the types to build things up, but that can usually be worked around with a fragment.

5 Likes

Thanks that’s the solution.

One more question how can I filter by a column name dynamically?

def by_filter_attribute(query, filter, filter_values) do
  from [m, a, mu, p, bf, l] in query,
  where: fragment("?.?_id in (?)", ^a, ^filter, ^filter_values)
end

I’m trying everything and nothing seems to work.

1 Like

That is what the field command is for. :slight_smile:

2 Likes