在 many_to_many 关系上过滤预加载
Filter preload on many_to_many relationship
我有两个模型:UserGroup
和 User
,具有 many_to_many
关系。
在我的用户组索引操作中,我做了这样的事情:
user_groups =
UserGroup
|> Repo.all
|> Repo.preload(:users)
并且,在视图中,当渲染用户组时,我做了这样的事情:
def render("index.json", %{user_groups: user_groups}) do
%{
user_groups:
Enum.map(user_groups, fn user_group ->
%{
id: user_group.id,
name: user_group.name,
users: user_group.users
}
end)
}
end
改变!现在用户有一个状态,我只想显示 active
个用户。
如何 "scope" 预加载用户以便只显示状态为 active
的用户?
您可以使用所需的 where
子句将部分查询传递给 Repo.preload
。假设 "active" 用户有 user.status == "active"
,你可以这样做:
user_groups =
UserGroup
|> Repo.all
|> Repo.preload(users: from(u in User, where: u.status == "active"))
您可以在 documentation 中阅读更多相关信息。
我有两个模型:UserGroup
和 User
,具有 many_to_many
关系。
在我的用户组索引操作中,我做了这样的事情:
user_groups =
UserGroup
|> Repo.all
|> Repo.preload(:users)
并且,在视图中,当渲染用户组时,我做了这样的事情:
def render("index.json", %{user_groups: user_groups}) do
%{
user_groups:
Enum.map(user_groups, fn user_group ->
%{
id: user_group.id,
name: user_group.name,
users: user_group.users
}
end)
}
end
改变!现在用户有一个状态,我只想显示 active
个用户。
如何 "scope" 预加载用户以便只显示状态为 active
的用户?
您可以使用所需的 where
子句将部分查询传递给 Repo.preload
。假设 "active" 用户有 user.status == "active"
,你可以这样做:
user_groups =
UserGroup
|> Repo.all
|> Repo.preload(users: from(u in User, where: u.status == "active"))
您可以在 documentation 中阅读更多相关信息。