【问题标题】:elixir, ecto, compare time in the where clauseelixir,ecto,比较where子句中的时间
【发布时间】:2015-05-13 09:47:53
【问题描述】:

当我在 Elixir 中使用 ecto 创建查询时,我不太确定如何在 'where' 子句中比较时间。

在架构部分,我将create_at 声明为:datetime

 schema "tenant" do
   field :id, :integer
   field :created_at, :datetime
   # timestamps([{:inserted_at,:created_at}])

 end

查询部分就像

def sample_query do
  query = from t in Tenant,
    where: t.id == 123,
    where: t.created_at == %Ecto.DateTime{{2015, 4, 27}, {10, 8, 42}},
    select: t
end

看来

where: t.created_at <= %Ecto.DateTime{{2015, 4, 27}, {10, 8, 42, 0}},

部分格式错误。谁能告诉我如何以正确的方式做到这一点?

PS:关于如何定义字段create_at,下面的链接给了我答案

Default datetime with Ecto & Elixir

【问题讨论】:

    标签: timestamp elixir ecto


    【解决方案1】:

    您不能像这样从 erlang 日期/时间元组创建 %Ecto.DateTime{} 结构。你需要做的:

    def sample_query do
      query = from t in Tenant,
        where: t.id == 123,
        where: t.created_at == ^Ecto.DateTime.from_erl({{2015, 4, 27}, {10, 8, 42, 0}}),
        select: t
    end
    

    如果您的时间值来自其他地方,并且您想自己创建 %Ecto.DateTime{} 结构,您可以这样做:

    ^%Ecto.DateTime{year: 2015, month: 4, day: 27, hour: 10, min: 8, sec: 42, usec: 0}
    

    (注意^)

    【讨论】:

    • 成功了!!!但似乎我需要定义created_attimestamps([{:inserted_at,:created_at}]) 而不是created_at: :datetime
    • 这对我不起作用。我仍然得到“不能在查询中强制转换为类型:datetime”我正在使用 ^ 并将 erl 日期转换为 Ecto.DateTime。 Ecto.DateTime.from_erl(:calendar.universal_time())
    • @JB: 如果你用一些有效的日期元组替换 :calendar 会起作用吗?如果是这样,您可能需要评估 :calendar 并在另一个变量中进行类型转换,然后在 where 子句中使用 ^variable。
    • 我相信您需要使用Ecto.DateTime 作为架构中的数据类型,而不是:datetime
    • @chrismcg 说的是真的。在这里发布问题并得到回答:stackoverflow.com/questions/30245703/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多