I have the following association.
Post belongs to User. User has many posts.
I have the following in the user schema
has_many :posts, MyApp.Posts.Post, foreign_key: :user_id
User with id 1 has POST_A, POST_B, POST_C
User with id 2 has POST_D, POST_E
I want to get a tuple in the following format
{
1: [
%Post{
id: 1,
name: postA,
},
%Post{
id: 2,
name: postB,
},
%Post{
id: 3,
name: postC,
}
],
2: [
%Post{
id: 4,
name: postD,
},
%Post{
id: 5,
name: postE
}
]
}
I tried writing the following query
posts_query =
Post
|> put_query_prefix(schema)
|> order_by([p], desc: p.inserted_at)
res =
User
|> put_query_prefix(schema)
|> preload([posts: ^posts_query])
|> select([u, p], {u.id, u.posts})
But this returns the following error:
field posts in select is a virtual field in schema.
Any suggestion how to resolve this?
- I tried using select_merge which didn’t work for me. Maybe I was wrong in framing the query.
- I do not want to enumerate the list since I have a large set of data and enumerating over such a long list wouldn’t be efficient.