我有团队,每个团队都有用户,所以有一个连接表将用户链接到团队,因为它有多对多关系,这是我的模型:
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>
?我没有要求以任何方式加载用户身份..那么为什么我会收到这样的警告呢?
我正在使用{:phoenix_ecto, "~> 3.0-rc}
答案 0 :(得分:9)
您需要预先加载: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