Searching in preload

i wrote a function that return its data + associated data also, but i want to select only id’s in associated data is it possible with preload ?

defp preload_favorite_books({favorite_books}) do
    {:ok, Repo.preload(favorite_books, :books)}
end

in books i only wants to return the books ids only

@hassamali you can do this with preload queries.

books_query = from b in Book, select: struct(b, [:id])
{:ok, Repo.preload(favorite_books, [books: books_query])}

As an aside, you have a single value wrapped in a tuple which is generally not a situation you want to end up in. It isn’t a huge issue but it is also basically pointless.

1 Like

What is this struct ?

https://hexdocs.pm/ecto/Ecto.Query.html#select/3

Its returning me the same struct + its association with no errors
not the association id

If you look closely at the association struct the only column with any data will be its ID column. If you set the logger to debug as well you’ll notice that it only queries the id from the database.

1 Like

{:ok,
[
%EmailMessaging.Favorites.Favorite{
meta: #Ecto.Schema.Metadata<:loaded, “favorites”>,
book: %EmailMessaging.Bookss.Book{
meta: #Ecto.Schema.Metadata<:loaded, “books”>,
book_id: nil,
favorites: #Ecto.Association.NotLoaded,
created_by: nil,
deleted_at: nil,
file_key: nil,
id: nil,
inserted_at: nil,
organization_uuid: nil,
repo_uuid: nil,
text: nil,
title: nil,
updated_at: nil,
uuid: “8ba50bbc-53a8-4637-a269-18bd95abeb93”
},
book_id: 1219,
deleted_at: nil,
id: 183,
inserted_at: ~U[2019-11-22 16:40:20.547609Z],
organization_uuid: nil,
updated_at: ~U[2019-11-22 16:40:20.547609Z],
user_uuid: “60749e79-67c6-4b90-be55-fa09c0bcac44”,
uuid: “ae9ab464-f429-4d9a-86a5-4cf51c7ebf8b”
}
]}

I got your point, got it now but i dont want this all struct all i want is {ok, uuid} and uuid will be association uuid

Do you even want preload then? Preload is about taking the parent entity and loading children within them. Do you only want the child uuids?

ids =
  favorite_books
  |> Ecto.assoc(:books)
  |> select([b], b.id)
  |> Repo.all
{:ok,ids}
1 Like

That worked, exactly what i am looking for little different but a decent way , i was trying to do this with preload. Thanks for your concern, Appreciated.

1 Like