王志軍
王志軍

Reputation: 1021

elixir, ecto, compare time in the where clause

When I create a query using ecto in Elixir, I'm not really sure about how to compare time in the 'where' clause.

In the schema part I declare create_at as :datetime

 schema "tenant" do
   field :id, :integer
   field :created_at, :datetime
   # timestamps([{:inserted_at,:created_at}])

 end

and the query part is like

def sample_query do
  query = from t in Tenant,
    where: t.id == 123,
    where: t.created_at == %Ecto.DateTime{{2015, 4, 27}, {10, 8, 42}},
    select: t
end

It seems that the

where: t.created_at <= %Ecto.DateTime{{2015, 4, 27}, {10, 8, 42, 0}},

part is of wrong form. Can someone tell me how to do it in the right way please?

PS: about how to define the field create_at, the link below gave me the answer

Default datetime with Ecto & Elixir

Upvotes: 7

Views: 2717

Answers (1)

chrismcg
chrismcg

Reputation: 1286

You can't create a %Ecto.DateTime{} struct from a erlang date/time tuple like that. You need to do:

def sample_query do
  query = from t in Tenant,
    where: t.id == 123,
    where: t.created_at == ^Ecto.DateTime.from_erl({{2015, 4, 27}, {10, 8, 42, 0}}),
    select: t
end

If your time values are coming from somewhere else and you want to create the %Ecto.DateTime{} struct yourself you could do:

^%Ecto.DateTime{year: 2015, month: 4, day: 27, hour: 10, min: 8, sec: 42, usec: 0}

(Note the ^)

Upvotes: 9

Related Questions