0

我正在查询 parse 上的关系数据,我希望对象按创建日期排序。我以前使用过这种方法,但无法使用关系数据获得有序查询。查询返回是随机顺序的。提前致谢!这是我的代码:

    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; 
     }
4

1 回答 1

0

我对你的代码有点困惑,

  1. 您创建一个“postQuery”并调用它,但从不使用它的任何数据。
  2. 还有一个 roomQuery 似乎从未被分配或使用过。
  3. 您正在按名称查询特定帖子。你在控制它的名字吗?如果没有,你应该使用 id's
  4. 什么是 PFRelation commentsRelation = [@"Comments"];

可能因为它只是一个片段,所以这些东西在其他地方处理;但是,对于我的回答,我假设您的“评论”字段是“评论”类对象的数组。

选项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 调用(毕竟根据调用来解析费用!)。

于 2014-02-02T16:57:19.497 回答