I have the below query with multiple left joins and preloads and it’s giving duplicate results if I don’t use the distinct, but by using the distinct, the order_by clause is not working. Below is the query. The query always returns the results in the same order no matter what I put inside order_by
.
Conversation
|> join(:left, [c], p in Participation,
on: p.conversation_id == c.id and p.user_id == ^visitor_id
)
|> join(:left, [c], m in Message, on: c.id == m.conversation_id)
|> where([_c, p], not is_nil(p.id))
|> preload([_, _, _], creator: :avatar, participants: :avatar)
|> distinct([c, _p], c.id)
|> order_by([c, _p], c.updated_at)
|> select([c, _, m], %{c | last_message: m})
Here is the query it produces.
#Ecto.Query<from c0 in Postgres.PostgresConversationRepository.Conversation,
left_join: p1 in Postgres.PostgresConversationRepository.Participation,
on: p1.conversation_id == c0.id and p1.user_id == ^"c23b2640-413a-4823-ab97-
49eccfe3dcfd",
left_join: m2 in Postgres.PostgresMessageRepository.Message,
on: c0.id == m2.conversation_id, where: not(is_nil(p1.id)),
order_by: [asc: c0.updated_at], limit: ^20, distinct: [asc: c0.id],
select: %{c0 | last_message: m2},
preload: [participants: [:avatar], creator: [:avatar]]>
How to make order_by
work with the above query.
Any help will be much appreciated.
Thank you.