首页 > 解决方案 > 使用 Ecto Fragments 将时间间隔添加到时间戳

问题描述

我想使用 Ecto 片段在 phoenix 应用程序中编写以下查询:

select *
from (
  select id, 
  inserted_at + interval '1 day' * expiry as deadline
  from friend_referral_code
) t
where localtimestamp at time zone 'UTC' > deadline

expiry 的值是一个整数值,表示天数。到目前为止,我得到的是这样的:

query = from frc in FriendReferralCode,
  where: fragment("localtimestamp at time zone 'UTC'") > fragment("? + INTERVAL '1' * ?", frc.inserted_at, frc.expiry)

FriendReferralCode
|> Repo.all(query)
|> Enum.each(fn frc -> update_friend_referral_code_users(get_friend_referral_code_users_by(receiver_id: frc.id), %{status: false}) end)
|> IO.puts()

结尾

但它会引发以下错误:

** (EXIT) an exception was raised:
        ** (FunctionClauseError) no function clause matching in Keyword.merge/2
            (elixir 1.11.2) lib/keyword.ex:764: Keyword.merge([], #Ecto.Query<from f0 in Stakester.Accounts.FriendReferralCode, where: fragment("localtimestamp at time zone 'UTC'") > fragment("? + INTERVAL '1 day' * ?", f0.inserted_at, f0.expiry)>)

标签: postgresqlelixirphoenix-framework

解决方案


你在查询间隔Ecto.Query.API.ago/2内部Ecto.Query.API.from_now/2 Ecto.Query.subquery/2select


此外,Repo.all/2需要一个查询作为第一个参数,而您FriendReferralCode在调用中作为第一个参数传递Repo.all/2,它需要一个查询,query作为第二个参数,它需要一个关键字选项列表。

只做query |> Repo.all()


推荐阅读