1
votes

I'm trying to query all of the leagues that belong to a particular user in my system.

The data setup looks like this:

USER MODEL:

has_many :users_leagues, Statcasters.UsersLeagues
has_many :leagues, through: [:users_leagues, :league]

So you can see, I have a has_many through association for users and leagues.

I'm trying to get a list of all the leagues a user has attached to it.

In rails it would look something like this: user.leagues and it would load up all of the leagues that have the current user id attached to it.

How can I do this with Ecto, Elixir and Phoenix?

1

1 Answers

4
votes

You can either preload leagues into user using Repo.preload:

user = user |> Repo.preload([:leagues])
# user.leagues is now a list of leagues

or use assoc and Repo.all to get a list of leagues for the user:

leagues = Ecto.assoc(user, :leagues) |> Repo.all