Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I preload association and get it returned in ecto?

Tags:

elixir

ecto

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?

like image 918
asiniy Avatar asked Oct 06 '16 13:10

asiniy


2 Answers

user = Repo.get(User, 1) |> Repo.preload([:posts])
like image 101
Zubair Nabi Avatar answered Sep 20 '22 14:09

Zubair Nabi


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]
...
like image 38
Dogbert Avatar answered Sep 20 '22 14:09

Dogbert