Append fields using select query on Ecto

I have a schema and it has many fields and one belongs_to association.
I want to query this model with one field of associated model like below.

def MyModel do
  schema "my_models" do
    field(:field0, :string)
    field(:field1, :string)
    field(:field2, :string)
    field(:field3, :string)
    field(:field4, :string)
    field(:field5, :string)
    field(:field6, :string)
    field(:field7, :string)
    field(:field8, :string)

    field(:other_model_id)
  end
end

def list() do
  MyModel
  |> join(:inner, [m], o in OtherModel, m.other_model_id == o.id)
  |> select([m, o], %{field0: m.field0, field1: m.field1, ... other_model_value: o.value})
end

But I don’t want to repeat field0, field1, …
Is there a better way to do this?

Thanks!

I found a way to do it.

def MyModel do
  schema "my_models" do
    field(:field0, :string)
    ...
    field(:field8, :string)

    field(:other_model_id, :integer)

    # Add a virtual field
    field(:other_model_value, :integer, virtual: true)
  end
end

def list() do
  MyModel
  |> join(:inner, [m], o in OtherModel, m.other_model_id == o.id)
  |> select([m, o], %{m | other_model_value: o.value})
end
2 Likes