I’m trying to preload and order a has_many
association. The associated children are preloaded, but not ordered according to the preload_order
. Here’s a simplified example:
# in the child module
schema "child" do
field :child_id, Ecto.UUID, primary_key: true
field :deleted_at, :utc_datetime
belongs_to :parent, Parent, references: :parent_id
end
# in the parent module
schema "parent" do
field :parent_id, Ecto.UUID, primary_key: true
has_many :children, Child,
foreign_key: :child_id,
where: [deleted_at: nil],
preload_order: [asc: :child_id]
end
# in a context module
Parent
|> where([p], p.parent_id in ^ids)
|> join(:left, [child], components in assoc(parent, :children))
|> preload([_, children], children: children)
|> Repo.all()
As I say, it’s the order of the children within each parent that I care about. But they don’t seem to be ordered by child_id
. For example, a child with %{child_id: "47bca378-4bc4-4919-8740-9e0ecf3c98be"}
occurs before %{child_id: "28eef785-815d-4ada-a6d2-baab4a03b3a7"}
.