2014-01-25 30 views
0

我在查詢關係數據的解析,我希望對象回來,他們被創建的日期排序。我以前使用過此方法,但一直無法使用關係數據獲得有序查詢。查詢返回的順序是隨機的。提前致謝!這裏是我的代碼:查詢關係分析關係數據不會回來排序使用orderedByAscending

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; 
    } 
+0

我沒有看到任何錯誤,只是閱讀代碼。你可以向我們展示一個評論中的數據樣本嗎? –

+0

「PFRelation * commentsRelation = [@」評論「];」 這段代碼甚至不應該編譯,你能修復它以顯示如何獲得commentsRelation嗎? –

回答

0

我有點困惑你的代碼,

  1. 您創建一個「postQuery」,並調用它,但從來沒有使用它的任何數據。
  2. 還有一個從未分配或使用過的roomQuery。
  3. 您正在通過名稱查詢特定帖子。你在控制它的名字嗎?如果沒有,你應該使用ID的
  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調用(解析基於呼叫後,所有費用!)。