问题
I can't find an efficient way to query Posts(PFObject) or Users(PFUser) classes and also have the isPostLiked(boolean) and isUserFollowed(boolean) included in the results array respectively.
Lets say, I have queried and received 25 Posts from the server. I want to fill in the like heart button with red if I have previously liked this Post. It would be very inefficient to query all the likes of these Posts and see if current user is contained in the results.
Is it possible to write a cloud code function to insert an 'isLiked' field to the query results and return it to the User for instance?
I am open to new strategies since I am stuck here. It is obvious that most of the social apps are having this need as a standard so there must be an effective solution. Thanks
回答1:
Your best action is to rid yourself of the relational database thinking. It seems to me you have a separate Likes class that tracks which user likes which post.
In the NoSQL space you should focus on your queries when you plan your datamodel. Ask yourself this question:
How do I want to query my data?
In this use case, I'm thinking you might want to
- Show how many likes a Post has
- Maybe show which users did like the Post
- Track whether the current user has liked a certain post
- Maybe find all the Posts the current user has liked?
To solve this, I would do the following:
- On the Post class, add a column likedby.
- On the User class, add a column likedposts. Both these columns are Array columns
Every time a user likes a post, you add a Pointer to the current user to the likedby array column for the Post AND a pointer to the post to the likedposts array column for the User.
This makes it very easy to
- find how many likes a post has (number of elements in likedby)
- list all the users that liked the post (using
query.includeKey("likedby")
on the Post) - check if the current user has already liked the post (if likedby array contains currentuser)
- list all the posts a user has liked (using
query.includeKey("likedposts")
on the User).
Use the same logic for followings.
来源:https://stackoverflow.com/questions/33575755/how-to-model-a-parse-class-to-include-isliked-isfollowing-fields-along-with-the