elixir - 在 Ecto 中,在带有连接的查询中使用查询函数
问题描述
我有 2 个模型Player
和Event
. 玩家有_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
有什么方法可以在包含联接的查询中使用此查询功能?
解决方案
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
也可能会有所帮助。
推荐阅读
- node.js - 每次用户上传图片时,Webpack 捆绑包构建都会使我的网站崩溃
- google-chrome - 更新 Chrome 扩展的“支持”/“联系开发者”页面
- c# - C# Razor - ViewModel 将空返回给控制器
- json - Golang json.Unmarshal 因任何明显原因无法正常工作
- windows - 在文件中搜索子字符串,但只检查前几个字符
- java - 在spring boot启动期间调用的tasklet执行方法
- java - JMS。错误解析的队列名称
- python - 由于各种原因随机无法使用列表
- numpy - 使用 numpy 获取非均匀样本
- python - 获取错误 selenium python:无法找到元素