我有一个拥有many_to_many关联的Phoenix App。在这个应用程序中:
我有一个用户表:
schema "users" do
field :username, :string
many_to_many :organizations, Organization, join_through: "memberships"
end
和组织表:
schema "organization" do
field :org_name, :string
many_to_many :members, Users, join_through: "memberships"
end
最后,我有会员资格表:
schema "memberships" do
field :role, :string
belongs_to :organization, Organization
belongs_to :user, User
end
我的问题:有没有很好的方法从成员资格对象中检索role
字段,以及单个SQL查询中的关联对象?我知道我可以在两个单独的查询中查询关联和关联对象,但我想知道是否有更简洁的方法来执行此操作。
答案 0 :(得分:1)
这样的事可以帮助你吗? 我没有对它进行测试,但它向您展示了预加载查询的想法:
首先在您的模型中添加has_many
会员资格字段,以便您可以预加载用户的会员资格:
schema "users" do
field :username, :string
many_to_many :organizations, Organization, join_through: "memberships"
has_many: :memberships, Membership # <- add this line
end
然后尝试如下请求:
import Ecto.Query
organization_id = ...
members_query =
from u in User,
join: m in Membership,
on: m.user_id == u.id and m.organization_id == ^organization_id,
preload: [memberships: m]
query =
from o in Organization,
where: o.id == ^organization_id,
preload: [members: ^members_query]
query |> YourApp.Repo.all