Although I am passing the query to repository inspired by this answer like this:
teams_users = Repo.all (from(t in Team, where: t.owner_id == ^user_id))
|> Enum.each( &team_users/1 )
def team_users (team) do
%{id: id} = team
Repo.all (from(tu in TeamUser, where: tu.team_id == ^id))
end
However, I got this error:
[error] GenServer #PID<0.450.0> terminating
** (Protocol.UndefinedError) protocol Enumerable not implemented for #Ecto.Query<from t in App.Team, where: t.owner_id == ^1>
(elixir) lib/enum.ex:1: Enumerable.impl_for!/1
(elixir) lib/enum.ex:116: Enumerable.reduce/3
(elixir) lib/enum.ex:1477: Enum.reduce/3
(elixir) lib/enum.ex:609: Enum.each/2
(App) web/channels/user_channel.ex:93: App.UserChannel.handle_in/3
(phoenix) lib/phoenix/channel/server.ex:223: Phoenix.Channel.Server.handle_info/2
(stdlib) gen_server.erl:615: :gen_server.try_dispatch/4
(stdlib) gen_server.erl:681: :gen_server.handle_msg/5
(stdlib) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
What I am trying to do is to get all the teams, then get the users of each team, then I expect to have all the users in one array.
Do I miss something? any advice? is there a better way to achieve this?
So you have an issue here with this code:
teams_users = Repo.all (from(t in Team, where: t.owner_id == ^user_id))
|> Enum.each( &team_users/1 )
You should remove the space between Repo.all
and (
teams_users = Repo.all(from(t in Team, where: t.owner_id == ^user_id))
|> Enum.each( &team_users/1 )
You could also write this as:
teams_users =
from(t in Team, where: t.owner_id == ^user_id)
|> Repo.all()
|> Enum.each( &team_users/1 )
However, doing this introduces an n + 1 query. You will make one query to fetch your teams, then another to fetch the team users. You should look into Repo.preload/2 for this.
teams_users =
from(t in Team, where: t.owner_id == ^user_id)
|> Repo.all()
|> Repo.preload(:team_users)
You are piping a query macro directly into Enum.each, instead of resolving the query with Repo.all and sending it into Enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With