The respective Ecto schema is set up correctly. I want to load all branches together with their categories, which in turn should include all products of that category which are available in that branch.
I defined a with_categories helper function in my Branch module:
def with_categories(query) do
from q in query,
join: c in assoc(q, :categories),
join: p in assoc(c, :products),
preload: [categories: {c, products: p}]
end
# usage:
Branch |> with_categories |> Repo.all
This gives me all branches with correct categories (e.g. a branch that doesn’t have products of a certain category will not have that category either), but the nested assocs category.products contain all products in that category, regardless of branch.
How can I apply the condition p.branch_id == q.id to the nested preload :products?
# Branch.ex
def with_categories(query) do
from q in query,
join: c in assoc(q, :categories),
join: p in assoc(q, :products), on: p.category_id == c.id,
preload: [categories: {c, products: p}]
end
This gives me the same result… I suspect that preloading does not respect the conditions of the original query.
The Ecto docs say that preload queries are possible, however I am currently not able (or do not understand how) to use the bound parameters q.id and c (q == Branch, c == Category) inside of a preload query.
I would like to use something like this as my preload query (this will not work because c, p and q are not bound to their values inside of the parent from context):
This looks entirely correct to me. You’re asking to preload all categories and for each category to preload all products. Nowhere in the query, there’s a constraint that a product should be of a particular branch.
You probably wanted something like:
def with_categories(query) do
from q in query,
join: c in assoc(q, :categories),
join: p in assoc(q, :products), on: p.branch_id == q.id,
preload: [categories: {c, products: p}]
end
Thanks for chiming in! I just tried adding branch_id to the constraints and now I get a list of all products (→ the full unconstrained set) in every category in every branch