Use dynamic values in a select map

So i read about the map 2 function in Ecto.Query.API and i have a scenario where i have to use it.
Query is is like this:

      from p in model,
       where: p.id == 1,
       select: map(p, [:id, :inserted_by, customer: [:id, :first_name]])

so instead of id and inserted_by which are hard coded. I want to use dynamic values in a list like this

      [:id, :inserted_by, :first_name]

How can i change the query for dynamic values?

Thanks.

From the docs:

map/2 can also be used to dynamically select fields:

fields = [:title, :body]
from p in Post, select: map(p, ^fields)

Yes i read that but i am talking about preload the associated fields as well

This example works for me, dynamically constructing the nested field list and interpolate into the query:

article_fields = [:id, :user_id, :body]             
author_fields = [:id, :bio]
fields = article_fields ++ [author: author_fields] 
Repo.all(from a in Blog.Article, preload: :author, select: map(a, ^fields))
1 Like