Reputation: 193
I am listing a list of records (Packs).
Those Packs are linked to items through a many to many relation :
When I am listing the packs, i'd like to preload their active items
def list_packs(params) do
packs = Pack
|> preload_active_items()
|> Repo.all()
|> Repo.preload([:classroom, [packlanguages: :language]])
end
defp preload_active_items(query) do
query
|> join(:left, [pack], _ in assoc(pack, :packitems))
|> join(:left, [_, pi], _ in assoc(pi, :item))
|> where([..., i], i.active == true)
|> preload([_, pi, i], [packitems: {pi, item: i}])
# |> preload([_, pi, i], [packitems: {pi, item: ^from(i, where: i.active == true)}])
end
Everything is working fine (I retrieve the packs and their preloaded items), but I get the packs filtered on those having an active item.
I tried to replace the where clause by the dashed line but the syntax is not correct.
Any idea ?
Upvotes: 2
Views: 1167
Reputation: 193
I found my way finally :
def list_packs(params) do
pi_query = from pi in PackItem,
join: i in assoc(pi, :item),
where: i.active == true
packs = Pack
|> Repo.all()
|> Repo.preload([:classroom, [packlanguages: :language, packitems: pi_query]])
end
Upvotes: 5