[Ecto] merge fields in select

Trying to select the age of patient, e.g.

from(
  p in Patient
  select: fragment("age(?)", p.dob),
  where: [id: ^id]
)
|> Repo.one()

However, the %Struct{} returned from db needs to have all/most fields present, but I would rather avoid typing it out, e.g.

...
  select: [p.name, p.email, fragment("age(?)", p.dob)]
...

Also, I would prefer if the query returns my %Struct{}. As it stand the select: [..fields..] returns list.

Can anyone help? :slight_smile:

Try select_merge

Thanks! Haven’t got that far in the docs…

Updated code:

from(
      p in Patient,
      select_merge: %{
        dob: fragment("to_char(?, 'DD MON YYYY')", p.dob),
        age: fragment("age(?)", p.dob)
      },
      where: [id: ^id]
    )
    |> Repo.one()

one might want to add some extra fields to %Struct{} for binding, e.g.

field :age, :string, virtual: true
1 Like