对Parse关系数据的查询不会使用orderedByAscending返回

时间:2014-01-25 03:55:00

标签: ios relational-database parse-platform pfquery

我正在查询解析时的关系数据,我希望这些对象按照它们创建日期的顺序返回。我之前已经使用过这种方法,但是无法使用关系数据获得有序查询。查询返回是随机顺序。提前致谢!这是我的代码:

    PFQuery *postQuery = [PFQuery queryWithClassName:@"Post"];
    [roomQuery whereKey:@"name" equalTo:self.postName];

    NSError *error;
    //done on main thread to have data for next query
    NSArray *results = [postQuery findObjects:&error];

    PFObject *post;

    if ([results count]) {
        post = [results objectAtIndex:0];
        NSLog(@"results were found");
    } else {
        NSLog(@"results were not found");
    }

    PFRelation *commentsRelation = [@"Comments"];
    [commentsRelation.query orderByAscending:@"createdAt"];
    [commentsRelation.query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            NSLog(@"Error Fetching Comments: %@", error);
        } else {
            NSArray *comments = objects; 
     }

1 个答案:

答案 0 :(得分:0)

我对你的代码感到有些困惑,

  1. 你创建了一个“postQuery”,然后调用它,但从不使用它的任何数据。
  2. 还有一个似乎从未被分配或使用的roomQuery。
  3. 您要按名称查询特定帖子。你在控制它的名字吗?如果没有,你应该使用id's
  4. 什么是PFRelation commentsRelation = [@“Comments”];
  5. 可能因为它只是一个片段,这些东西在别处处理;但是,对于我的回答,我假设你的“评论”字段是一个“评论”类对象的数组。

    选项1:

    PFQuery * postQuery = [PFQuery queryWithClassName:@"Post"];
    [postQuery whereKey:@"name" equalTo:self.postName]; 
    // again, possibly an id field would be more reliable
    // [postQuery whereKey:@"objectId" equalTo:self.postId];
    [postQuery includeKey:@"Comments"];
    PFObject * post = [postQuery getFirstObject];// no need to download all if you just want object at [0]
    // this will contain your post and all of it's comments with only one api call
    // unfortunately, it's not sorted, so you would have to run a sort.
    NSArray * comments =  [post[@"Comments"] sortedArrayUsingComparator: ^(id obj1, id obj2) {
        return [obj1[@"createdAt" compare: obj2[@"createdAt"];
    }];
    

    选项2:

    也许更好的选择是重新设计数据结构,而不是将评论与帖子相关联,您可以将帖子与评论相关联(如在解析文档中)

    PFQuery * postQuery = [PFQuery queryWithClassName:@"Post"];
    [postQuery whereKey:@"name" equalTo:self.postName]; 
    // again, possibly an id field would be more reliable
    // [postQuery whereKey:@"objectId" equalTo:self.postId];
    
    PFQuery * commentQuery = [PFQuery queryWithClassName:@"Comment"];
    [commentsQuery whereKey:@"parent" matchesQuery:postQuery]; // when creating a comment, set your post as its parent
    [commentsQuery addOrderDescending:@"createdAt"]
    [commentQuery findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
        // comments now contains the comments for myPost
    }];
    

    上述两种解决方案都避免了额外的不必要的api呼叫(毕竟根据呼叫解析费用!)。