我正在尝试查看当前用户的团队是否与传入的用户团队重叠。我有一些有效的方法,但我想知道是否可以提高效率。这是我所拥有的:
user_teams = from(
t in MyApp.Team,
left_join: a in assoc(t, :accounts),
where: p.owner_id == ^user.id or (a.user_id == ^user.id and t.id == a.project_id)
) |> Repo.all
current_user_teams = from(
t in MyApp.Team,
left_join: a in assoc(t, :accounts),
where: t.owner_id == ^current_user.id or (a.user_id == ^current_user.id and p.id == a.project_id)
) |> Repo.all
然后我将它们与:
Enum.any?(user_teams, fn(t) -> t in current_user_teams end)
再次,这符合我的需求,但似乎可能有更好的方法呢?
答案 0 :(得分:1)
最简单的解决方案是将这两个查询合并为一个,并检查结果查询是否返回任何内容。因此,我们完全可以这样做:
query = from t in MyApp.Team,
left_join: a in assoc(t, :accounts),
where: p.owner_id == ^user.id or (a.user_id == ^user.id and t.id == a.project_id),
where: t.owner_id == ^current_user.id or (a.user_id == ^current_user.id and p.id == a.project_id),
limit: 1,
select: true
not is_nil(Repo.one(query))
这将模拟来自PostgreSQL的SELECT EXIST (…)
查询(在Ecto 3.0中,将有Repo.exist?/1
函数可以做到这一点,related issue)。
默认情况下,where
个重复的AND
片段将被>