Ecto query -> how to return a data struct

I have a simple question… but i am having trouble wrapping my head around it:

I have a simple query like:

query = from(a in "artists", select: a.id, where: is_nil(a.bit_id) )
Repo.all(query)

i realy want back an array of structs, rather than a set of ids… but i can’t seen to word my query correctly. If take the select out, i get:

queries that do not have a schema need to explicitly pass a :select clause in query:

Any ideas on how I should be doing this?

Thanks!

1 Like

If you have an Artist schema, you can do:

query = from(a in MyApp.Artist, where: is_nil(a.bit_id) )
Repo.all(query)
3 Likes

With a schema-less query like in your example, you manually need to select all the fields you want returned since Ecto favors explicitness over implicitness. It could default to automatically select all the fields in the table when not providing a select option, but would that be a good default?

Use the schema query as advised above, and Ecto will automatically select all the fields you declared in your schema (not necessarily all the fields in your database table).

2 Likes

I have this same question. How would you take the results of an arbitrary query and map them to some struct, like an embedded schema or otherwise?

https://hexdocs.pm/ecto/Ecto.Repo.html#c:load/2 is handy for that.

4 Likes

Yes, I got it to work with mapped_list = list |> Enum.map(&(Repo.load(Schema, &1)))

1 Like