【问题标题】:Preload association with non-default belongs_to atom与非默认 belongs_to 原子的预加载关联
【发布时间】:2016-08-06 01:57:01
【问题描述】:

我正在使用 Ecto 2.0 并尝试运行此查询:

query = from e in EmpireInstance,
        where: e.user_id == ^user.id,
        preload: [:board]

board 的架构如下所示:

schema "board_instances" do  
  belongs_to :empire, PlexServer.EmpireInstance
  has_many :board_pieces, BoardTileInstance

  timestamps
end

EmpireInstance 架构:

schema "empire_instances" do
  ...

  belongs_to :user, PlexServer.User
  has_one :board, PlexServer.BoardInstance
  ...

  timestamps
end

我收到此错误:

** (Ecto.QueryError) deps/ecto/lib/ecto/association.ex:392:where 中的字段 PlexServer.BoardInstance.empire_instance_id 在查询中的架构中不存在:

from b in PlexServer.BoardInstance,
   where: b.empire_instance_id in ^[1],
   select: {b.empire_instance_id, b}

看起来它仍在尝试使用 module_name + _id 的默认 belongs_to id。除了将 belongs_to 原子改回默认值之外,有没有办法解决这个问题?

这是查询的代码:

def show(conn, _) do
  user = Guardian.Plug.current_resource(conn)

  query = from e in EmpireInstance,
        where: e.user_id == ^user.id,
        preload: [:board]

  case Repo.one(query) do
    nil -> 
      conn
      |> put_status(:unprocessable_entity)
      |> json(%{errors: ["No associated empire"]})
    empire ->  
      render(conn, PlexServer.EmpireInstanceView, "show.json", empire: empire)
  end
end

【问题讨论】:

  • 能否添加EmpireInstance的架构?
  • @Dogbert 你去!
  • 您确定错误消息是针对问题顶部的查询吗? (只是想确认一下。)
  • @Dogbert 我在查询的地方添加了代码。我 90% 确定它来自查询。
  • 谢谢,看起来不错。我也很困惑为什么它使用empire_instance_idbelongs_todocumentation 暗示它应该使用关联名称+_id,所以empire_id。如果在belongs_to :empire, PlexServer.EmpireInstance 之后添加, foreign_key: :empire_id 会发生什么?

标签: elixir ecto


【解决方案1】:

来自has_one/3 文档:

:foreign_key - 设置外键,这应该映射到另一个架构上的字段,默认为当前架构的下划线名称,以_id为后缀

由于current_schema是empire_instance,所以key是empire_instance_id

也许你的belongs_tohas_one 弄错了?或者您以错误的方式在数据库中创建了密钥。

如果没有,您能否发布您的迁移文件?

【讨论】:

  • 啊,我的 has_xxx 关联中缺少 :foreign_key!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
相关资源
最近更新 更多