Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 872
王志軍 Avatar asked May 13 '15 09:05

王志軍


1 Answers

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 ^)

like image 119
chrismcg Avatar answered Sep 18 '22 15:09

chrismcg