Let say I have a User
model which has_many
Post
.
I fetched a user:
user = Repo.get(User, 1)
and now I want to get all posts for this user. The only solution I found is to:
posts = Repo.preload(user, :posts).posts
But it's ugly. Is there any shorthand for that?
user = Repo.get(User, 1) |> Repo.preload([:posts])
You can use Ecto.assoc/2
to get a query for all the posts and then pass that to Repo.all/1
to actually fetch them:
iex(1)> user = Repo.get(User, 1)
iex(2)> Ecto.assoc(user, :posts)
#Ecto.Query<from p in MyApp.Post, where: p.user_id == ^1>
iex(3)> Ecto.assoc(user, :posts) |> Repo.all
[debug] QUERY OK source="posts" db=2.4ms
SELECT p0."id", p0."title", p0."user_id", p0."inserted_at", p0."updated_at" FROM "posts" AS p0 WHERE (p0."user_id" = $1) [1]
...
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