ecto
ecto copied to clipboard
Schema `preload_order` cannot be overriden by passing ordered query
Elixir version
Elixir 1.17.3 (compiled with Erlang/OTP 27)
Database and Version
PostgreSQL 17.0
Ecto Versions
ecto 3.12.4
Database Adapter and Versions (postgrex, myxql, etc)
postgrex 0.19.2
Current behavior
# in Blog.Comment schema
...
field(:likes, :integer)
# in Blog.Post schema
...
has_many(:comments, Comment, preload_order: [asc: :likes])
# in Blog context
query = from(p in Post, preload: [comments: ^from(c in Comment, order_by: [desc: :likes])])
Repo.all(query)
# => results ordered by ascending likes
comments: [%Comment{likes: 1, ...}, %Comment{likes: 42, ...}]
Expected behavior
I would have expected the order_by
from the preload query (^from(c in Comment, order_by: [desc: :likes])]
) to take precedence over the schema ordering preload_order: [asc: :likes]
.
If however, it is not a bug but an expected feature, would it be possible to achieve this in some other way?
- setting some default ordering in the schema, which works most of the times
- in some specific function, we need a different ordering overriding the default