Search code examples
elixirecto

Is it possible to do select on preload in ecto query?


I need to select specific fields from the Post schema which have 10+ fields. I need to select preloaded :comments as well. How can I do that?

query = from p in Post, preload: [:comments], select: map(p, [:comments, :title])
Repo.all(query)

Solution

  • There are multiple ways of doing this, depending on what kind of data structure you want to receive as output. If you want a %Post{} struct with only the comments and title fields, use the following query:

    query = from p in Post, preload: [:comments], select: [p.comments, p.title]
    Repo.all(query)
    

    Otherwise, please refer to the documentation for the select query expression :-)