【问题标题】:Make Ecto queries more efficient使 Ecto 查询更高效
【发布时间】:2018-07-24 22:01:53
【问题描述】:

我正在尝试查看我当前用户的团队是否与传入的用户团队重叠。我有一些有用的东西,但我很好奇它是否能让我更有效率。这是我所拥有的:

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)

同样,这符合我的需求,但似乎有更好的方法来做到这一点?

【问题讨论】:

  • 您是否在此请求的后面使用user_teamscurrent_user_teams?如果是这样,我想您需要保持原样,但如果不是,您可以只执行一个查询,如果给定用户和当前用户都是团队的一部分,则只获取团队。

标签: elixir phoenix-framework ecto


【解决方案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 片段将是ANDed。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多