Given following database structure:
struct User {
id: Uuid,
name: String
}
struct Post {
id: Uuid,
user_id: Uuid,
subject: String,
comment: String
}
struct AssignedPosts {
id: Uuid,
user_id: Uuid,
post_id: Uuid,
comment: String
}
I would like to extend the User
and Post
structs so that they can hold a list of posts, assigned users and assigned posts like this:
struct User {
id: Uuid,
name: String,
posts: Option<Vec<Post>>,
assignedPosts: Option<Vec<Post>>
}
struct Post {
id: Uuid,
user_id: Uuid,
subject: String,
comment: String,
user: Option<User>,
assignments: Option<Vec<AssignedPosts>>
}
struct AssignedPosts {
id: Uuid,
user_id: Uuid,
post_id: Uuid,
comment: String,
user: Option<User>,
post: Option<Post>
}
This is like rails handles associations and lets the user fetch associated items with optimized sql calls.
I currently have no idea of how to fetch the assigned users to all posts a user created. So considering I have a user id in first place, I want to fetch the posts, what can be done by calling belonging_to(&user)
but I do not see a way to easily fetch the associated users through AssignedPosts
from there on.
The only idea I have is following:
- Mapping all post ids and fetch the
AssignedPost
usingeq_any
. - Looping through the
AssignedPost
items, collecting user ids and fetching the users witheq_any
. - Looping through the fetched
AssignedPost
items and assigning theUser
matchinguser_id
. - Looping through the posts and adding
AssignedPost
items matching bypost_id
.
The obvious reason for needing AssignedPost
ist that it holds meta data for the connection between user and post.
Is there a better way?