解析PFRelation复杂搜索

时间:2016-01-21 04:27:57

标签: ios parse-platform pfquery pfrelation

我正在使用Parse构建一个iOS应用程序,它有一些复杂的查询并且在使用PFRelation时会遇到麻烦。

这是一个人们提交文章的社交网站。您可以关注其他用户并查看他们提交的文章。您还可以根据主题进行搜索。

这是我的代码

PFQuery* query = [PFQuery queryWithClassName:@"Article"];

//remove articles this user has seen or submitted
[query whereKey:@"likedBy" notEqualTo:currentUser]; //'likedBy' is a relation
[query whereKey:@"dislikedBy" notEqualTo:currentUser]; //'dislikedBy' is a relation
[query whereKey:@"submittedBy" notEqualTo:currentUser]; //'submittedBy' is a relation

[query whereKey:@"tagArray" containedIn:tags];
[query orderByDescending:@"createdAt"];

PFRelation* relation = [currentUser relationForKey:@"following"]; //following is a relation for the user
PFQuery* followingQuery = [relation query];
[followingQuery findObjectsInBackgroundWithBlock:^(NSArray* results, NSError* error) {

    //results from this first query is the list of people the user is following

    [query whereKey:@"submittedBy" containedIn:results]; //submitted by is a relation on the article
    [query findObjectsInBackgroundWithBlock:^(NSArray* results, NSError* error) {

        /* This will return all the items that match the tags set above.
        However, if there are no tags, I do not get the articles
        that match the "submittedBy" above. It is empty */
        completion(results);
    }];

}];
}

感谢您抽出宝贵时间阅读本文。

1 个答案:

答案 0 :(得分:0)

我能够通过创建子查询来解决此问题:

PFQuery* query = [PFQuery queryWithClassName:@"Article"];

//remove articles this user has seen or submitted
[query whereKey:@"likedBy" notEqualTo:currentUser]; //'likedBy' is a relation
[query whereKey:@"dislikedBy" notEqualTo:currentUser]; //'dislikedBy' is a relation
[query whereKey:@"submittedBy" notEqualTo:currentUser]; //'submittedBy' is a relation

[query whereKey:@"tagArray" containedIn:tags];

// create an array to hold all of the queries
NSMutableArray* queryArray = [NSMutableArray arrayWithCapacity:10];

PFRelation* relation = [currentUser relationForKey:@"following"]; //following is a relation for the user
PFQuery* followingQuery = [relation query];
[followingQuery findObjectsInBackgroundWithBlock:^(NSArray* results, NSError* error) {

    //results from this first query is the list of people the user is following
   for (PFObject* user in results) {
            //create a new query for each result and add it to the query array
                    PFQuery* querySub = [PFQuery queryWithClassName:@"App"];
                     [querySub whereKey:@"submittedBy" equalTo:user];
                     [queryArray addObject:querySub];
                }

                //query all of the queries at once
                PFQuery* finalQuery = [PFQuery orQueryWithSubqueries:queryArray];

    [finalQuery findObjectsInBackgroundWithBlock:^(NSArray* results, NSError* error) {
    //NOTE: you cannot sort via query with subqueries, so I had to sort the results array when completed
           …...
    }];

}];
}