I want to load associations on an existing struct
entity |> Repo.preload(:components)
executes this query:
SELECT c0."id", c0."type", c0."entity_id", c0."data", c0."inserted_at", c0."updated_at", c0."entity_id" FROM "components" AS c0 WHERE (c0."entity_id" = $1) ORDER BY c0."entity_id" [<<251, 46, 32, 129, 153, 58, 78, 91, 168, 158, 158, 49, 192, 85, 194, 36>>]
I noticed there is a default sort of ORDER BY c0."entity_id"
(where does that come from?)
I want to change the sort order, so I tried:
entity |> Repo.preload(components: from(c in Component, order_by: c.type))
However, instead of replacing the order by
completely, it only appended my column to the default sort order:
SELECT c0."id", c0."type", c0."entity_id", c0."data", c0."inserted_at", c0."updated_at", c0."entity_id" FROM "components" AS c0 WHERE (c0."entity_id" = $1) ORDER BY c0."entity_id", c0."type" [<<251, 46, 32, 129, 153, 58, 78, 91, 168, 158, 158, 49, 192, 85, 194, 36>>]
This is unintuitive, as I’m still not sorting by the column I specified. How do I get rid of the ORDER BY c0."entity_id"
part and replace it with ORDER BY c0.type
?
Here are my schemas:
Entity:
defmodule Thexr.Spaces.Entity do
use Ecto.Schema
import Ecto.Changeset
@derive {Jason.Encoder, only: [:id, :parent_id, :name, :type, :components]}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "entities" do
field :name, :string
field :type, :string
field :space_id, Ecto.UUID
field :parent_id, :binary_id
has_many :components, Thexr.Spaces.Component
timestamps()
end
Component
defmodule Thexr.Spaces.Component do
use Ecto.Schema
import Ecto.Changeset
import PolymorphicEmbed, only: [cast_polymorphic_embed: 3]
@derive {Jason.Encoder, only: [:type, :data]}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "components" do
field :type, :string
belongs_to :entity, Thexr.Spaces.Entity
field :data, PolymorphicEmbed,
types: [
position: Thexr.Components.Vector3,
rotation: Thexr.Components.Vector3,
scale: Thexr.Components.Vector3
],
on_type_not_found: :raise,
on_replace: :update
timestamps()
end