简体   繁体   中英

How can i count the number of followers using parse saved data as shown:

i have saved my followers list as shown in the table image在此处输入图片说明

in the "user" column , i've saved the objectId of user being followed and in the "follower" column i've saved the currentUser (follower) now i want to get the number of followers of each user.. how can i do that?

Parse Query for counting objects https://parse.com/docs/ios/guide#queries-counting-objects Where you can execute 1 query to get followers count of 1 user. Which can easily max out parse api limit ie (counting object query 160 requests per minute). For this Parse and Me, both not recommend you to use counting Objects especially if you expect significant number of users.

Parse Recommendation to avoid Count Operations https://parse.com/docs/ios/guide#performance-avoid-count-operations

You should use parse cloud code( https://parse.com/docs/ios/guide#cloud-code ) and have a key in your User table which can keep record of current followers count for that user.

Cloud code in your case.

Parse.Cloud.afterSave("Followers", function(request) {
    if(request.object.existed() == true)
        // No need to increment count for update due to some reason
        return;
    });
    // Get the user id for User
    var userID = request.object.get("user");// Or request.object.get("user").id;
    // Query the user in actual User Table
    var UserQuery = Parse.Object.extend("User");
    var query = new Parse.Query(UserQuery);
    query.get(userID).then(function(user) {
    // Increment the followersCount field on the User object
        user.increment("followersCount");
        user.save();
    }, function(error) {
        throw "Got an error " + error.code + " : " + error.message;
    });
});

Unfollowing might also happen, Leaving After Delete practise to you https://parse.com/docs/ios/guide#cloud-code-afterdelete-triggers

You can use the Parse Server countObjectsInBackground() function for achieve your task. It worked for me. I have used iOS SDK version 1.17.3 .

Here is the Swift 4 sample code:

    let query = PFQuery(className: "yourTableName")
    query.whereKey("user", equalTo: "yourUserId")
    query.countObjectsInBackground { (count: Int32, error: Error?) in
    if error == nil {
        print("My followers number: \(count)")
    }

For more information: https://docs.parseplatform.org/ios/guide/#counting-objects

Hope it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM