silverdr
Has_many through load selected associated columns
Building on the example from another thread:
https://forum.elixirforum.com/t/many-to-many-once-again-extra-data-on-the-join-table/
User has many Chatroom through UsersChatrooms.
Now, I would like to get names and ids of given user’s chatrooms. I surely can do for example:
user = Repo.preload(user, :chatrooms)
but this will load “everything” from both final and join tables, while I’d rather do something like Rails’ pluck or at least select so that only columns I am interested in are queried. What are the “correct” ways of doing this with Ecto associations?
Alternatively already while fetching the user record
Marked As Solved
LostKobrakai
You can use ecto query to select what you need. There’s not really a high level API for that in ecto.
query =
from cr in Chatroom,
join: ucr in assoc(:users_chatrooms),
on: ucr.user_id == ^user_id and ucr.chatroom_id == cr.id,
select: map(cr, [:id, :name])
Repo.all(query)
or
user
|> Ecto.assoc(:chatrooms)
|> select([cr], map(cr, [:id, :name])
|> Repo.all()
Also Liked
LostKobrakai
Ecto only fetches the fields present in the schema anyways. You could even have multiple schemas for a single table, but different use cases. If you’re hardly fetching all fields of a schema I’d wonder if the schema is well defined or if you’d not rather want to split it into multiple.
LostKobrakai
Ecto is far more geared towards giving developers the ability to deal with the sql. It’s not an ORM and doesn’t try to be. One could probably built one on top of ecto. I can see this not being great when trying to get things of the ground, but it’s really great once you need to maintain that thing flying.
dimitarvp
Yep, more or less. And it’s important to remember that Ecto is explicit: it tries very hard not to do things you didn’t ask it to do.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









