【发布时间】: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