首页 > 解决方案 > 通过关联查询

问题描述

我有一个表格的 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。

标签: elixirphoenix-frameworkecto

解决方案


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)
...

推荐阅读