from p in Post, preload: [comments: :likes]`
from(p in Post,
preload: [:comments, comments: :likes],
select: p)
Are these queries identical (same number of SQL query) and do they return, both, all posts, their associated comments, and the associated likes for those comments?
Both queries come from the documentation of the Ecto.Query module v2.2.8.
Please, some explanations.
If you don’t explicitly join the data you specified to be preloaded ecto will be preloading them in separate queries. Both those queries will preload comments and likes of comment, but I’d say the latter example does seem a bit redundant. I’m not even sure it’s valid, because for Ecto.Repo.preload mixing atom and keyword list notation does not work (the related docs update). So I’d avoid it just to not cause confusion.
Yes. They’d be the same. Keep in my mind preloading that way without the joins will make more than 1 query to the database. You can rewrite it with joins to do it in one query.
query =
from p in Post,
join: c in assoc(p, :comments),
join: l in assoc(c, :likes),
preload: [
comments: {c, likes: l}
]
Repo.all(query)