Ecto中has_many through关联预加载失败问题求助
问题解决建议
错误出在through关联的字段名上,你在User和Gym的schema里误用了复数形式的字段名,而UserGym中定义的关联是单数的:gym和:user。
修正后的代码:
Mp.Schema.User
defmodule Mp.Schema.User do use Ecto.Schema import Ecto.Changeset schema "users" do # ... has_many :user_gyms, Mp.Schema.UserGym, on_replace: :delete # 将 :gyms 改为 :gym,对应 UserGym 里的 belongs_to :gym has_many :gyms, through: [:user_gyms, :gym] end end
Mp.Schema.Gym
defmodule Mp.Schema.Gym do use Ecto.Schema import Ecto.Changeset schema "gyms" do # ... has_many :user_gyms, Mp.Schema.UserGym, on_replace: :delete # 将 :users 改为 :user,对应 UserGym 里的 belongs_to :user has_many :users, through: [:user_gyms, :user] end end
另外建议在引用其他schema时加上完整模块名(比如Mp.Schema.UserGym),避免因模块加载顺序问题导致的潜在错误。
修正后再执行你的预加载查询:
query = from U in Mp.Schema.User, preload: :gyms Mp.Repo.all(query)
就能正常工作了。
内容的提问来源于stack exchange,提问作者Rasna Shakya
相关产品推荐
相关产品推荐

