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

Why I got #Ecto.Association.NotLoaded?

我有团队,每个团队都有用户,所以有一个 table 到 link 用户到团队的连接,因为它是多对多关系,这是我的模型:

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