How to do the LiveComponent preload example in Ash.Query?

In the docs for the Phoenix.LiveComponent (https://hexdocs.pm/phoenix_live_view/Phoenix.LiveComponent.html#module-preloading-and-update) there is a section there that shows how to use preload/1 to solve the N+1 problem:
def preload(list_of_assigns) do
list_of_ids = Enum.map(list_of_assigns, & &1.id)

users =
from(u in User, where: u.id in ^list_of_ids, select: {u.id, u})
|> Repo.all()
|> Map.new()

Enum.map(list_of_assigns, fn assigns ->
Map.put(assigns, :user, users[assigns.id])
end)
end
def preload(list_of_assigns) do
list_of_ids = Enum.map(list_of_assigns, & &1.id)

users =
from(u in User, where: u.id in ^list_of_ids, select: {u.id, u})
|> Repo.all()
|> Map.new()

Enum.map(list_of_assigns, fn assigns ->
Map.put(assigns, :user, users[assigns.id])
end)
end
How would I do the query in this section in Ash.Query?
4 Replies
ZachDaniel
ZachDaniel3y ago
You'd do basically the same thing.
require Ash.Query #<- need this

def preload(list_of_assigns) do
list_of_ids = Enum.map(list_of_assigns, & &1.id)

users =
User
|> Ash.Query.for_read(:primary_read) # <- whatever your action is called
|> Ash.Query.filter(id in ^list_of_ids)
|> YourApi.read!()
|> Map.new(&{&1.id, &1})

Enum.map(list_of_assigns, fn assigns ->
Map.put(assigns, :user, users[assigns.id])
end)
end
require Ash.Query #<- need this

def preload(list_of_assigns) do
list_of_ids = Enum.map(list_of_assigns, & &1.id)

users =
User
|> Ash.Query.for_read(:primary_read) # <- whatever your action is called
|> Ash.Query.filter(id in ^list_of_ids)
|> YourApi.read!()
|> Map.new(&{&1.id, &1})

Enum.map(list_of_assigns, fn assigns ->
Map.put(assigns, :user, users[assigns.id])
end)
end
Terryble
TerrybleOP3y ago
So instead of doing a select, just execute the query normally and then use Map.new to produce the same result as the example above?
ZachDaniel
ZachDaniel3y ago
Yeah, there isn't much of a point in doing select: {u.id, u} anyway its a convenience
Terryble
TerrybleOP3y ago
Alright. Thanks!

Did you find this page helpful?