I have a entity X
that has_many
of entity Y
. I create a base query to retrieve X
and then make a join
to get Y
and then in select
I choose which fields I want from both X
and Y
, however this results in duplicated data.
Example:
from(x in X, as: :x)
|> join(:inner, [x], y in assoc(x, :y), as: :y)
|> select(%{
id: as(:x).y,
y: [%{
id: as(:y)/id,
status: as(:y).status
}]
})
result:
[
%X{id: 1, y: [%Y{id: 1, status: "pending"}]},
%X{id: 1, y: [%Y{id: 2, status: "canceled"}]},
%X{id: 1, y: [%Y{id: 3, status: "running"}]},
]
I want tio achieve this result:
[
%X{id: 1, y: [
%Y{id: 1, status: "pending"},
%Y{id: 2, status: "canceled"},
%Y{id: 3, status: "running"}
]},
]
how can I translate this to Ecto.Query
? I tried to sue a subquery but I don’t know if it’s the best option