问题描述
我有团队,每个团队都有用户,因此有一个联接表将用户链接到团队,因为它具有多对多关系,这是我的模型:
I have teams and each team has users, so there is a join table to link users to teams as its a many to many relation, here is my models:
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
如果我运行查询以获取一个用户的所有团队以及所有结果团队的用户,就像这样:
If I run a query to get all teams of a user with all resulted teams's users, like this:
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上加载用户..为什么我会收到这样的警告?
In the log, I got team with id 1, and all its users with ids: (3, 4, 5)But why I got user: #Ecto.Association.NotLoaded<association :user is not loaded>
? I didn't ask to load the user at that id any way.. so why I got such warning?
我正在使用{: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
There is a section on nested associations in the docs. https://hexdocs.pm/ecto/Ecto.Query.html#preload/3
这篇关于为什么我收到#Ecto.Association.NotLoaded?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!