这是我的模特:
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&lt;现在&lt; 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
有什么想法吗?
答案 0 :(得分:1)
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
答案 1 :(得分:0)
除了Dogbert的回答,您可能希望更改架构以使用ecto架构中的NaiveDateTime
或DateTime
类型,并使用Ecto.DateTime
/ {来自标准库的{1}}模块来操作值。
自Ecto 2.1起,myApp.onPageInit
类型有been deprecated,看起来像scheduled to be removed in Ecto 2.2。