Reputation: 883
I'm saving user "Likes" as a relation to Post objects, just like in the docs.
$user = ParseUser::getCurrentUser();
$post= new ParseObject("Post", $the_post_id);
$relation = $user->getRelation("likes");
$relation->add($post);
$user->save();
This works fine so far.
Now I'm wondering how to query the Posts and also pull a Count of how many users liked each post. I don't want to run separate queries in a loop for each Post.
I would also like to know if the CurrentUser likes each post in the query as well. Again, definitely want to avoid making multiple queries in a loop.
Is this possible?
My Current Post Query:
$query = new ParseQuery("Post");
$posts = $query->find();
Upvotes: 3
Views: 1398
Reputation: 2020
[...] pull a Count of how many users liked each post [...]
Create a likes counter field in the Post class, and update it each time the Post is added/removed in a "likes" relation. You'll find this suggested in more than one place (for example, here and here).
Use Parse's increment method (with positive or negative value) to atomically update the counter.
[...] know if the CurrentUser likes each post [...]
This is hard without multiple queries. You know it's easy to get the posts liked by the user:
$postsLiked = $relation->getQuery()->find();
You may also manage to get the posts that are not in a "likes" relation with the user. You might try using this kind of information, but you'd have to accept a reduction of simplicity in your script, along with a possible level of inaccuracy (remember that you can't retrieve more than 1000 results with a single Parse query). You may find it preferable to only show the information as a detail in the single post view (the information could also be dynamically fetched via AJAX upon an input event related to the single post entry or depending on the current visibility of the entries inside the viewport).
Upvotes: 5