这是我的模型:
schema "fixtures" do
field :sm_id, :integer
field :local_score, :integer
field :visitor_score, :integer
field :local_pen_score, :integer
field :visitor_pen_score, :integer
field :ht_score, :string
field :ft_score, :string
field :et_score, :string
field :starting_at, Ecto.DateTime
belongs_to :local_team, Team, foreign_key: :local_team_id
belongs_to :visitor_team, Team, foreign_key: :visitor_team_id
belongs_to :season, Season
belongs_to :round, Round
timestamps()
end
我想要的是使用以下查询获取活动灯具:
def fixtures_live(query, round_) do
now = Ecto.DateTime.utc |> Ecto.DateTime.cast!
query
|> join(:left, [r], f in assoc(r, :fixtures))
|> where([r, _], r.id == ^round_.id)
|> where([_, f], f.starting_at < ^now)
|> where([_, f], datetime_add(f.starting_at, 2, "hour") > ^now)
|> select([_, f], f)
end
我所做的如下: starting_at < now < starting_at +2“小时”
结果是:
Ecto.Query.CastError at GET /sports/get_all_fixtures
web/models/round.ex:73: value `#Ecto.DateTime<2017-08-02 16:32:29>` in `where` cannot be cast to type :naive_datetime in query:
如果我想演绎成:
|> where([_, f], datetime_add(f.starting_at, 2, "hour") |> Ecto.DateTime.cast! > ^now)
结果是:
Compiling 11 files (.ex)
== Compilation error in file web/models/round.ex ==
** (Ecto.Query.CompileError) `Ecto.DateTime.cast!(datetime_add(f.starting_at(), 2, "hour"))` is not a valid query expression
(ecto) expanding macro: Ecto.Query.where/3
(sopitas) web/models/round.ex:73: Sopitas.Round.fixtures_live/2
(ecto) expanding macro: Ecto.Query.select/3
(sopitas) web/models/round.ex:74: Sopitas.Round.fixtures_live/2
(elixir) expanding macro: Kernel.|>/2
(sopitas) web/models/round.ex:74: Sopitas.Round.fixtures_live/2
(elixir) lib/kernel/parallel_compiler.ex:121: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1
有什么想法吗?
发布于 2017-08-02 17:04:24
datetime_add
为defined以返回:naive_datetime
。为了能够将其与值进行比较,now
也应该是可以强制转换为:naive_datetime
的类型。Ecto.DateTime
不能转换为:naive_datetime
,但您可以使用Elixir中的新NaiveDateTime
模块。
只需更改:
now = Ecto.DateTime.utc |> Ecto.DateTime.cast!
至:
now = NaiveDateTime.utc_now
发布于 2017-08-02 21:19:54
除了Dogbert的回答之外,您可能还希望更改模式以使用ecto模式中的:naive_datetime
或:utc_datetime
类型,并使用标准库中的NaiveDateTime
/ DateTime
模块来操作这些值。
从Ecto 2.1开始,Ecto.DateTime
类型具有been deprecated并且看起来像是scheduled to be removed in Ecto 2.2。
https://stackoverflow.com/questions/45466493
复制相似问题