在Ecto中使用虚拟字段以及数据查询
defmodule Friends.Person do
use Ecto.Schema
import Ecto.Query
schema "people" do
field(:first_name, :string)
field(:last_name, :string)
field(:age, :integer, default: 0)
field(:create_time, :utc_datetime_usec)
field(:create_time_str, :string, virtual: true)
end
def changeset(person, params \\ %{}) do
person
|> Ecto.Changeset.cast(params, [:first_name, :last_name, :age, :create_time])
|> Ecto.Changeset.validate_required([:first_name, :last_name], message: "参数不能为空")
end
def find_by_id(id) do
person = Friends.Repo.get!(Friends.Person, id)
{_, time_str} = Friends.DatetimeFormat.format_datetime_local!(person.create_time)
Map.put(person, :create_time_str, time_str)
end
def find_by_id_merge() do
Friends.Repo.all(
from(p in Friends.Person,
select_merge: %{
create_time_str: fragment("TO_CHAR(create_time, 'YYYY-MM-DD HH24:MI:SS')")
}
)
)
end
end