Skip to content

Commit 12a214a

Browse files
authored
Add section about how to reference the parent in a subquery (#4610)
1 parent b5e6877 commit 12a214a

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

guides/howtos/Aggregates and subqueries.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,21 @@ MyApp.Repo.one(query)
8787

8888
Because the query does not specify a `:select` clause, it will return `select: p` where `p` is controlled by `MyApp.Post` schema. Since the query will return all fields in `MyApp.Post`, when we convert it to a subquery, all of the fields from `MyApp.Post` will be available on the parent query, such as `q.visits`. In fact, Ecto will keep the schema properties across queries. For example, if you write `q.field_that_does_not_exist`, your Ecto query won't compile.
8989

90+
If you need to reference the parent in the subquery, you can do so using named bindings in the parent query and `Ecto.Query.API.parent_as/1` in the subquery. Here is an example:
91+
92+
```elixir
93+
inner_query =
94+
from c in Comment,
95+
where: parent_as(:posts).id == c.post_id
96+
97+
query =
98+
from p in Post,
99+
as: :posts,
100+
inner_lateral_join: c in subquery(inner_query)
101+
102+
MyApp.Repo.one(query)
103+
```
104+
90105
Ecto also allows an Elixir map to be returned from a subquery, making the map keys directly available to the parent query.
91106

92107
Let's see one last example. Imagine you manage a library (as in an actual library in the real world) and there is a table that logs every time the library lends a book. The "lendings" table uses an auto-incrementing primary key and can be backed by the following schema:

0 commit comments

Comments
 (0)