gpt4 book ai didi

elixir - 为什么我得到#Ecto.Association.NotLoaded?

转载 作者:行者123 更新时间:2023-12-04 02:11:40 25 4
gpt4 key购买 nike

我有团队,每个团队都有用户,因此有一个联接表将用户链接到团队,这是多对多关系,这是我的模型:

defmodule App.Team do
use App.Web, :model

schema "teams" do
field :owner_id, :integer
has_many :team_users, {"team_user", App.TeamUser}
end

end
defmodule App.User do
use App.Web, :model

schema "users" do
# field :email, :string
has_many :team_user, App.TeamUser
end
end


这是联接模型:

defmodule App.TeamUser do
use App.Web, :model

@primary_key false
schema "team_user" do
belongs_to :user, App.User
belongs_to :team, App.Team
end

end


如果我运行查询以获取一个用户的所有团队以及所有结果团队的用户,如下所示:

teams_users =
from(t in Team, where: t.owner_id == ^user_id)
|> Repo.all()
|> Repo.preload(:team_users)


我得到此日志:

[%App.Team{__meta__: #Ecto.Schema.Metadata<:loaded>, id: 1,
is_base_team: true, owner_id: 3,
team_users: [%App.TeamUser{__meta__: #Ecto.Schema.Metadata<:loaded>,
team: #Ecto.Association.NotLoaded<association :team is not loaded>,
team_id: 1,
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 3},
%App.TeamUser{__meta__: #Ecto.Schema.Metadata<:loaded>,
team: #Ecto.Association.NotLoaded<association :team is not loaded>,
team_id: 1,
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 4},
%App.TeamUser{__meta__: #Ecto.Schema.Metadata<:loaded>,
team: #Ecto.Association.NotLoaded<association :team is not loaded>,
team_id: 1,
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 5}]}]


在日志中,我得到了ID为1的团队,其ID为(3,4,5)的所有用户。
但是为什么我得到 user: #Ecto.Association.NotLoaded<association :user is not loaded>?我没有要求以任何方式在该ID上加载用户。.为什么我会收到这样的警告?

我正在使用 {:phoenix_ecto, "~> 3.0-rc}

最佳答案

您需要预加载:user:team_users

teams_users =
from(t in Team, where: t.owner_id == ^user_id)
|> Repo.all()
|> Repo.preload(team_users: :user)


文档中有关于嵌套关联的部分。 https://hexdocs.pm/ecto/Ecto.Query.html#preload/3

关于elixir - 为什么我得到#Ecto.Association.NotLoaded?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37564255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com