Owens
Preload only first nested association's association
Hello all,
I’m doing a DB call for the index page of a WhatsApp-style chat app.
I have ChatsUsers -> Chats -> Messages.
I need to get the list of the user’s chats ordered by recency of the last_message, and just for the first Chat preload all of its Messages.
See below for reference.
Here’s the DB call I’m trying to make
ChatUser
|> where(user_id: ^user_id)
|> join(:left, [cu], c in assoc(cu, :chat))
|> order_by([cu, c], [{:desc, c.last_message}])
|> preload([cu, c], chat: c)
|> Repo.all()
This will order all the ChatsUsers based on the descending order of its chat.last_message.
But now I need to preload the messages to only the first ChatsUsers’s chat.
Any tips appreciated!
Most Liked
LostKobrakai
Why “preload” the messages in the first place? I’d load load those messages separately (in liveview components are great for that).
fuelen
Hello!
For my use case I used this:
threads # list of structs
|> MyApp.Repo.preload(messages: {MyApp.Chat.recent_messages_in_thread(), [:author]})
defmodule MyApp.Chat do
def recent_messages_in_thread(query \\ MyApp.Chat.Message) do
from messages in query,
distinct: messages.thread_id,
order_by: [asc: messages.thread_id, desc: messages.inserted_at]
end
end
I hope the idea is clear
fuelen
Actually, my snipped loads only the last message for every thread.







