我需要进行复杂的查询,以了解商店是否在一天中的特定时间营业。这是部分查询。
current_time = %Time{(time_now |> DateTime.to_time()) | microsecond: {0, 0}}
current_time_string = time_now |> DateTime.to_time() |> Time.to_string()
MyApp.StoreSchedule
|> where(
[rs],
rs.from_weekday < rs.to_weekday and rs.from_weekday <= ^current_weekday and
rs.to_weekday >= ^current_weekday and
((rs.open_time < rs.close_time and rs.open_time <= ^current_time and
rs.close_time >= ^current_time) or
(rs.close_time < rs.open_time and rs.open_time <= ^current_time and
fragment("'23:59:59' >= ?", ^current_time_string)))
)
|> having([rs], count(rs.id) > 0)
|> group_by([rs], rs.store_id)
|> select([rs], %{store_id: rs.store_id, count: count(rs.id)})
这很好,但是我在考虑是否有某种方法可以删除fragment/2
部分。我尝试了几种方法,但都没有成功。
示例1:
and '23:59:59' >= ^current_time
给出错误:
value `~T[18:35:14]` in `where` cannot be cast to type {:array, :integer} in query:
示例2:
and ^~T[23:59:59] >= ^current_time
给出错误:
** (ArgumentError) Postgrex expected a binary, got {23, 59, 59, 0}. Please make sure the value you are passing matches the definition in your table or in your query or convert the value accordingly.