【问题标题】:Elixir/Phoenix Ecto preload associations not working for has_manyElixir/Phoenix Ecto 预加载关联不适用于 has_many
【发布时间】:2017-10-17 08:04:45
【问题描述】:

我快疯了。现在在我的问题上工作了半天,但找不到解决方案/错误。创建一个聊天,我得到了一个聊天模型和一个以用户模型作为外键的 chat_user 模型。

Chat 有很多has_many :chat_users, Test.Chat.ChatUser, foreign_key: :chat_id,chat_user 有belongs_to :user, Test.User 和belongs_to :chat, Test.Chat.Chat。

我正在预加载关联:

  defp preload_associations(chat, params \\ nil) do
    Repo.preload(chat, [
     :chat_users
   ])
  end

我得到的错误是:** (Postgrex.Error) ERROR 42703 (undefined_column): column c0.user_id does not exist

数据库中的表chat_users 的字段user_id 带有一个外键。在我看来,Ecto 正在聊天中搜索 user_id 而不是 chat_user。

知道我做错了什么吗?谢谢。

编辑:模型

defmodule Test.Chat.ChatItem do
@moduledoc false

use Test.Web, :model

schema "chats" do
  field :name, :string
  ...
  has_many :chat_users, Test.Chat.ChatUser, foreign_key: :chat_id
  timestamps()
end


defmodule Test.Chat.ChatUser do
use Test.Web, :model

schema "chat_users" do
  ...
  belongs_to :user, Test.User
  belongs_to :chat, Test.Chat.Chat
end

和

defmodule Test.User do
...

【问题讨论】:

  • 你最好在这里发布你的模型,模型中的错误比文字描述更容易发现。
  • 尝试从has_many定义中删除foreign_key: :chat_id。
  • 而且...您真的要预加载 chat_users,还是要预加载用户?
  • 删除外键导致* (Ecto.QueryError) deps/ecto/lib/ecto/association.ex:495: field Test.Chat.ChatUser.chat_item_id in where does not exist in the schema in query。是的。我要预加载chat_users,下一步是从chat_users 中预加载用户。 chat_users 有我需要的字段和用户。 REST-Api,在响应中一次需要所有的东西。

标签: associations elixir phoenix-framework ecto preload


【解决方案1】:

最后我发现了错误。与我的迁移或模型无关。该问题是由某些环境配置引起的。构建开发和测试数据库的脚本没有删除测试数据库,因此它在 chat_users 表中没有 user_id。该错误发生在 docker 容器内的 mix test 中,因此发现错误并不容易。我是 elixir 的新手,但仍然讨厌 stacktrace,曾经阅读过一些不错的 c# stacktrace ;) 但感谢您的帮助。

【讨论】:

  • 这可能是因为您已经运行了迁移,然后对其进行了更改。在这种情况下,您有责任修复混乱。我做MIX_ENV=test mix do ecto.drop, ecto.create, ecto.migrate。
猜你喜欢
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
相关资源
最近更新 更多