Is it possible to dynamically fetch data using Ecto
?
I found &Ecto.Query.API.map/2, but I can’t setup it properly for in dynamic single query.
Let’s say we have simple blog app.
With first example:
query = from p in Post,
inner_join: a in assoc(p, :author),
select: map(p, [:author_id, :title, author: [:first_name, :last_name]])
Repo.all(query)
I have list of maps with only :author_id
and :title
fields.
With second example:
query = from p in Post,
inner_join: a in assoc(p, :author),
select: map(p, [:title, :author_id, author: [:first_name, :last_name]])
Repo.all(query)
I received KeyError
for :first_name
(association not loaded).
Finally with third example:
query = from p in Post,
preload: :author,
select: map(p, [:title, :author_id, author: [:first_name, :last_name]])
Repo.all(query)
I received all info which I want, but not without any problems:
- Firstly I achieved it in 2 queries instead of 1.
- Secondly I was need to add extra field
:author_id
(as in documentation).
It’s not a big problem with writing such query manually, but I tried to find a way to fetch data dynamically. Can you help me with it?