Search code examples
elixirecto

Field `Struct` in `where` does not exist in the model source in query


Having an issue using has_many and belongs_to, I have these two models:

  @primary_key {:guid, :integer, []}
  schema "characters" do
    field :name, :string
    field :race, :integer
    field :class, :integer
    field :gender, :integer
    field :level, :integer
    field :xp, :integer
    field :money, :integer
    field :online, :integer
    field :totaltime, :integer
    field :leveltime, :integer
    field :rest_bonus, :float
    field :is_logout_resting, :integer
    field :honor_highest_rank, :integer
    field :honor_standing, :integer
    field :stored_honor_rating, :float
    field :stored_dishonorable_kills, :integer
    field :stored_honorable_kills, :integer
    field :health, :integer
    field :power1, :integer
    field :power2, :integer
    field :power3, :integer
    field :power4, :integer
    field :power5, :integer
    belongs_to :account, Pugit.Account, references: :id
  end

And this Account model

 schema "account" do
    field :username, :string
    field :sha_pass_hash, :string
    field :gmlevel, :integer, default: 0
    field :sessionkey, :string
    field :v, :string
    field :s, :string
    field :email, :string
    field :joindate, Ecto.DateTime
    field :last_ip, :string, default: "0.0.0.0"
    field :failed_logins, :integer, default: 0
    field :locked, :integer, default: 0
    field :last_login, Ecto.DateTime
    field :active_realm_id, :integer, default: 0
    field :expansion, :integer, default: 0
    field :mutetime, :integer, default: 0
    field :locale, :integer, default: 0

    has_many :characters, PugitWow.Character, foreign_key: :account
  end

I'm trying to run this query:

Pugit.AccountRepo.all(Pugit.Account) |> Pugit.CharRepo.preload([:characters])

The only big difference here is that maybe I'm trying to preload from a different repo (other database)

But I get this error:

** (Ecto.QueryError) deps/ecto/lib/ecto/association.ex:320: field `Pugit.Character.account` in `where` does not exist in the model source in query:

from c in Pugit.Character,
  where: c.account in ^[1, 2, 3, 4, 21],
  order_by: [asc: c.account]

    (elixir) lib/enum.ex:1473: Enum."-reduce/3-lists^foldl/2-0-"/3
    (elixir) lib/enum.ex:1151: Enum."-map_reduce/3-lists^mapfoldl/2-0-"/3
      (ecto) lib/ecto/repo/queryable.ex:91: Ecto.Repo.Queryable.execute/5
      (ecto) lib/ecto/repo/queryable.ex:15: Ecto.Repo.Queryable.all/4
    (elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2

Any information would be great thanks

The Primary Key for my characters table is guid

The Foreign Key for my characters table is account

The Primary Key for my account table is id


Solution

  • This is happening because your account association uses the same name as the field for the foreign key, account. Rename that field to account_id, and then use this as your association:

    belongs_to :account, Pugit.Account