Ecto / Elixir,我如何按日期查询?

时间:2017-04-08 10:21:23

标签: datetime elixir ecto

我正在处理我的应用的统计信息页面,并尝试按日期查询数据。

要获取日期范围,请使用Calendar.Date

date_range = Date.days_after_until(start_date, end_date, true)
|> Enum.to_list

它返回日期的日期列表,每个日期看起来像"2017-04-07"。因此,根据我从date_range获得的日期,我尝试查询,但它会触发如下错误。

where cannot be cast to type Ecto.DateTime in query: from o in Myapp.Order, where: o.created_date >= ^~D[2017-04-07]

对于Order的created_date字段,我这样做了字段, field :created_date, Ecto.DateTime

如果我想按日期查询,我该如何查询?

提前感谢。

1 个答案:

答案 0 :(得分:21)

您似乎正在尝试比较日期和日期时间。您需要将其中一个投射到另一个类型,以便进行比较,例如将数据库中的日期时间转换为日期:

date = ~D[2017-01-01]
from p in Post, where: fragment("?::date", p.inserted_at) >= ^date

或将Elixir Date转换为NaiveDateTime

{:ok, datetime} = NaiveDateTime.new(date, ~T[00:00:00])
from p in Post, where: p.inserted_at >= ^datetime

如果您有开始日期和结束日期,则只需添加and即可。您不需要使用任何库生成整个日期列表。

from p in Post,
  where: fragment("?::date", p.inserted_at) >= ^start_date and
         fragment("?::date", p.inserted_at) <= ^end_date

from p in Post,
  where: p.inserted_at >= ^start_datetime and
         p.inserted_at <= ^end_datetime