elixir - 通过关联查询
问题描述
我有一个表格的 ecto 查询:
def query_clicks(user, freq \\ "day", filters \\ []) do
from(Click)
|> select(
[c],
[
fragment("date_trunc(?,?) as t", ^freq, c.inserted_at), count(c.link_id) ]
)
# |> where([c], c.user.id == 1) # Didn't work
|> where([c], ^filters)
|> group_by([c], fragment("t"))
|> Repo.all
end
Click
有一个关联:
has_one :user, through: [:link, :user]
我想要做的是获得用户的点击,(什么是 user.clicks in rails)。我该怎么做?
我正在使用凤凰 1.4。
解决方案
user
从 开始然后通过可能更具可读性assoc/2
:
user
|> assoc(:clicks)
|> select(
[c],
[
fragment("date_trunc(?,?) as t", ^freq, c.inserted_at), count(c.link_id) ]
)
|> where([c], ^filters)
|> group_by([c], fragment("t"))
|> Repo.all()
当然,假设您的User
架构中有正确的关联,我猜这将是:
has_many :links, Link
has_many :clicks, through: [:links, :clicks]
以及将通讯员添加has_many :clicks
到您的Link
架构中。
但你也可以从Click
你正在做的事情开始:
Click
|> join(:inner, [c], l in Link, on: c.link_id == l.id and l.user_id == ^user.id)
...
推荐阅读
- openstreetmap - Nominatim search.php 不工作,而 reverse.php 工作正常
- php - 如何使 xampp 不显示目录列表?
- reactjs - 组件通信 - React JS
- javascript - 未在元素上触发单击事件
- wordpress - WordPress 商店定位器无法在 Internet Explorer 上运行
- python-3.x - IndentationError::expected 一个缩进块
- angular - Angular + Jest + ChartJS - ReferenceError:图表未定义
- git - 用于 Windows Git 安装的可选 Unix 工具
- c# - SSRS 2016:将报表加载到服务器时出现 NullReferenceException 和 ReportServerException
- python-3.x - 如何优化此 python 代码以对大输入进行排序?