如何使用ecto获取上周的记录

时间:2015-11-30 12:06:53

标签: elixir ecto

MyApp.Order
    |> where([m], m.inserted_at > datetime_add(^Ecto.DateTime.utc, -2, "week"))
    |> where([m], m.inserted_at < datetime_add(^Ecto.DateTime.utc, 0, "week"))

datetime_add(^Ecto.DateTime.utc, 0, "week")似乎没有成为本周。因此,此查询从上周和当前周提取记录。

可替换地,

  defp weekly_orders do
    {interval1, interval2} = week_intervals
    MyApp.Order
    |> where([m], m.inserted_at >= datetime_add(^Ecto.DateTime.utc, ^interval1, "day"))
    |> where([m], m.inserted_at < datetime_add(^Ecto.DateTime.utc, ^interval2, "day"))
  end

  defp week_intervals do
    {-(day_of_the_week + 6) , -(day_of_the_week - 1)}
  end
  defp day_of_the_week do
    :erlang.date
    |> :calendar.day_of_the_week
  end

周一因datetime_add(Ecto.DateTime.utc, 0, "day")

而失败
  1. datetime_add(Ecto.DateTime.utc, 0, "day")返回或表示什么?
  2. 使用ecto查询上周记录的正确方法是什么?

3 个答案:

答案 0 :(得分:2)

datetime_add(Ecto.DateTime.utc,0,&#34; day&#34;)将0天添加到当前日期时间,因此它基本上什么都不做。

我在这里使用日期而不是日期时间,因为您对一周中的几天真的更感兴趣。也许像

这样的东西
distance_to_monday = -(:erlang.date |> :calendar.day_of_the_week) + 1
distance_to_sunday = 7 - (:erlang.date |> :calendar.day_of_the_week)

MyApp.Order
  |> where([m], m.inserted_at >= date_add(^Ecto.Date.utc, ^distance_to_monday, "day"))
  |> where([m], m.inserted_at <= date_add(^Ecto.Date.utc, ^distance_to_sunday, "day")

答案 1 :(得分:2)

您需要使用Timex

 room_messages = Repo.all(
        from m in Message,
        where: m.inserted_at >= ^Timex.beginning_of_day(Timex.now), where: 
        m.inserted_at <= ^Timex.end_of_day(Timex.now),

      )

答案 2 :(得分:0)

几年后,还会使用 Timex 并执行以下操作:

MyApp.Order
|> where([m], m.inserted_at >= ^Timex.subtract(Timex.now, Timex.Duration.from_days(7)))
相关问题