I initially had this raw SQL query that I needed to translate
select * from entities e
join users on users.id = e.user_id
left join (select user_countries.* from user_countries
join countries on user_countries.country_id = countries.id and countries.real_estate_id = ?) as a on a.user_id = users.id
where
e.assurance_id = ?
and e.state in (?, ?)
order by e.created_at desc;
And I was able to translate this to Ecto query
query =
from entity in Entity,
join: u in assoc(entity, :user),
left_join:
a in subquery(
from user_country in UserCountry,
join: country in Country,
on: user_country.country_id == country.id,
where: country.real_estate_id == ^real_estate_id,
select: %{
country_assoc_user_id: user_country.user_id,
id: country.id,
name: country.name,
created_at: country.created_at,
updated_at: country.updated_at
}
),
on: a.country_assoc_user_id == u.id,
where:
entity.assurance_id == ^assurance_id and
entity.state in ^states
order_by: [desc: entity.created_at],
limit: ^limit,
select: %{
entity
| user: %{
u
| countries: [
%{
id: a.id,
name: a.name,
created_at: a.created_at,
updated_at: a.updated_at
}
]
}
}
query
|> Repo.all()
|> merge_countries()
Is this is the most elegant way to do this? Also it seems to me like it’s a lot of work to merge countries under user using custom code in Elixir inside merge_countries()