saint
How to Query a User with has_many Post in Ecto
def get_all_post_by_user(user_id) do
query = from u in User,
where: u.id == ^user_id,
join: p in Post, on: p.user_id == u.id,
select: %{
user_id: u.id,
username: u.username,
title: p.title,
description: p.description
}
query |> Repo.all
end
i have this query but when i try to render it, it returns multiple set of data but same User with different Post.
like this.
[
%{user_id: 1,
username: "saint",
title: "test1",
description: "sample1"},
%{user_id: 1,
username: "saint",
title: "test2",
description: "sample2"}
]
Thanks in advance.
Marked As Solved
idi527
I think that’s how table joins work. In psql you would get multiple rows. Maybe try Repo.preload or Ecto.Query.preload.
Also Liked
benwilson512
Welcome! We’re happy to help. In order for that to be possible though, it’s important that you provide full and complete information showing the code you tried, and the errors you got.
idi527
is it true?
It might be. Depends on the amount of data that you query.
A join or Ecto.Query.preload might be evil as well since then ecto would have to parse multiple almost identical rows like in your example and then put them all into some “parent” struct. Repo.preload, which fires a second query, might be more efficient in that case.
joaquinalcerro
Last Post!
aphelion00
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
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









