sudochop
Ecto has_many through with condition/filter
I’ve got an existing database with an interesting permissions model. The permissions schema are based on a php library called Spatie Permissions. Long story short, I need to join my User’s roles through a model_has_roles table. model_has_roles is generic and allows any model in the system to have roles via a model_type field. For sake of brevity, what I’m trying to do is create an association for this query:
from r in Role,
inner_join: mhr in "model_has_roles",
on: mhr.role_id == r.id,
where: mhr.model_id == ^user.id,
where: mhr.model_type == "App\\User"
Unfortunately the docs say :where - A filter for the association. See "Filtering associations" below. It does not apply to :through associations.
Am I out of luck? Ultimately I just want track the roles / preload them right on the User model.
Marked As Solved
sudochop
So I think I figured this out. I was going about it completely wrong. I think this does what I need:
many_to_many :roles, Role,
join_through: ModelHasRole,
join_keys: [model_id: :id, role_id: :id],
join_where: [model_type: "App\\User"]
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









