通过关联查询

时间:2019-02-11 12:23:32

标签: elixir phoenix-framework ecto

我有一个如下形式的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]

我想做的是获得用户的点击(在rails中是user.clicks)。我该怎么办?

我正在使用Phoenix 1.4。

1 个答案:

答案 0 :(得分:0)

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