首页 > 解决方案 > 在 Ecto 中,在带有连接的查询中使用查询函数

问题描述

我有 2 个模型PlayerEvent. 玩家有_many 事件。我有一个 ecto 查询,它获得了最高得分者,如下所示:

from(p in Player,
  join: s in assoc(p, :events),
  group_by: [p.id],
  select: %{total_goals: count(s.id), player: p},
  where: s.type == "goal_scored",
  where: p.team_id == ^team_id,
  order_by: [desc: count(s.id)],
  limit: 10
)
|> Repo.all()

这很好用,但在我的Event模型中,我有一个方便的函数来只查询类型的事件goal_scored

def goals(query) do
  from(e in query, where: e.type == "goal_scored")
end

有什么方法可以在包含联接的查询中使用此查询功能?

标签: elixirecto

解决方案


Ecto.Query.dynamic/2是你的朋友吗?直接使用 in 中的完整查询是不可能的Event,但您可以这样拆分:

def goal_scored_condition do
  dynamic([e], e.type == "goal_scored")
end

def goals(query) do
  conditions = goal_scored_condition()
  from(e in query, where: ^conditions)
end

并且在Player

conditions = Event.goal_scored_condition()
from(p in Player,
  ...
  where: ^conditions,
  ...

在某些情况下,Ecto.Query.subquery/2也可能会有所帮助。


推荐阅读