我能够像下面这样将简单的PFQuery转换为它的REST等价物:
PFQuery
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'999Z'"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; NSString *createdAt = [dateFormatter stringFromDate:createdAtDate]; PFQuery *query = [PFQuery queryWithClassName:@"Photo"]; [query whereKey:@"createdAt" lessThan:createdAt]; [query orderByDescending:@"createdAt"]; [query setLimit:10]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects,NSError *error) { if (!error) { //Etc... } }];
REST API请求:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.'999Z'"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; NSString *createdAt = [dateFormatter stringFromDate:createdAtDate]; NSString *dateQueryString = [NSString stringWithFormat:@"{\"createdAt\":{\"$lte\":{\"__type\":\"Date\",\"iso\":\"%@\"}}}",createdAt]; NSDictionary* parameters = @{@"order": @"-createdAt",@"limit": @10,@"include": @"user",@"where":dateQueryString}; AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer = [AFJSONRequestSerializer parseSerializer]; // Already has App-Id,App-key and Content-Type set. NSMutableURLRequest* request = [manager.requestSerializer requestWithMethod:@"GET" URLString:@"https://api.parse.com/1/classes/Photo" parameters:parameters error:nil]; AFHTTPRequestOperation* operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation,id responSEObject) { // Etc.. } failure:^(AFHTTPRequestOperation *operation,NSError *error) { NSLog(@"%@",error.localizedDescription); }]; [operation start];
然而问题是复合查询如下所示:
NSMutableArray* subqueriesArray = [NSMutableArray array]; PFQuery *followingActivitiesQuery = [PFQuery queryWithClassName:@"Activity"]; [followingActivitiesQuery whereKey:@“type” equalTo:@“Follow”]; [followingActivitiesQuery whereKey:@“fromUser” equalTo:[PFUser currentUser]]; followingActivitiesQuery.limit = 1000; PFQuery *privateUserQuery = [PFUser query]; [privateUserQuery whereKey:@“yourMomLikedThisPhoto” equalTo:[NSNumber numberWithBool:NO]]; // fake whereKey of course PFQuery *photosFromFollowedUsersQuery = [PFQuery queryWithClassName:@"Photo"]; [photosFromFollowedUsersQuery whereKey:@“yourMomLikedThisPhoto” equalTo:[NSNumber numberWithBool:YES]]; [photosFromFollowedUsersQuery whereKey:@“user” matchesKey:@“toUser” inQuery:followingActivitiesQuery]; [photosFromFollowedUsersQuery whereKey:@“user” matchesQuery:privateUserQuery]; PFQuery *photosFromCurrentUserQuery = [PFQuery queryWithClassName:@"Photo"]; [photosFromCurrentUserQuery whereKey:@“yourMomLikedThisPhoto” equalTo:[NSNumber numberWithBool:YES]]; [photosFromCurrentUserQuery whereKey:@“user” equalTo:[PFUser currentUser]]; [subqueriesArray addObject:photosFromFollowedUsersQuery]; [subqueriesArray addObject:photosFromCurrentUserQuery]; PFQuery *query = [PFQuery orQueryWithSubqueries:subqueriesArray]; [query includeKey:@"Photo"]; [query orderByDescending:@"createdAt"];
如果有人可以帮我理解如何为此构建参数,我真的很感激.关于如何朝着正确方向前进的一般想法也会有所帮助.我已经提到了Parse REST API Guide,但我似乎无法得到它.我正在尝试使用$inQuery来正确使用它,但还没有运气.
这个问题的答案将涵盖使用Parse REST API(在iOS上)查询时遇到的大多数常见和复杂问题.
解决方法
我认为您要做的是使用您选择的库(AFNetworking)将以下调用转换为相关的http调用.如您所见,子查询行为嵌入在特定的编码URL中,该URL包含带有字典的数组,该字典的值是带有比较语句的字典.
curl -X GET \ -H "X-Parse-Application-Id: ${APPLICATION_ID}" \ -H "X-Parse-REST-API-Key: ${REST_API_KEY}" \ -G \ --data-urlencode 'where={"$or":[{"wins":{"$gt":150}},{"wins":{"$lt":5}}]}' \ https://api.parse.com/1/classes/Player
(source)
子类查询
您可以使用类方法查询来查询特定子类的对象.以下示例查询用户可以承受的装甲:
PFQuery *query = [Armor query]; [query whereKey:@"rupees" lessThanOrEqualTo:[PFUser currentUser][@"rupees"]]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects,NSError *error) { if (!error) { Armor *firstArmor = [objects firstObject]; // ... } }];
(source)
关系查询
有几种方法可以为关系数据发出查询.如果要检索字段与特定PFObject匹配的对象,可以使用whereKey:equalTo:就像其他数据类型一样.例如,如果每个Comment在其post字段中都有一个Post对象,则可以获取特定Post的注释:
// Assume PFObject *myPost was prevIoUsly created. // Using PFQuery PFQuery *query = [PFQuery queryWithClassName:@"Comment"]; [query whereKey:@"post" equalTo:myPost]; [query findObjectsInBackgroundWithBlock:^(NSArray *comments,NSError *error) { // comments now contains the comments for myPost }]; // Using NSPredicate NSPredicate *predicate = [NSPredicate predicateWithFormat:@"post = %@",myPost]; PFQuery *query = [PFQuery queryWithClassName:@"Comment" predicate:predicate]; [query findObjectsInBackgroundWithBlock:^(NSArray *comments,NSError *error) { // comments now contains the comments for myPost }];
One Parse Blog Post还提到可以使用以下方法进一步增强谓词:
At this time,we support these NSPredicate features:
Simple comparisons such as =,!=,<,>,<=,>=,and BETWEEN with a key
and a constant. Containment predicates,such as x IN {1,2,3}.
Key-existence predicates,such as x IN SELF. BEGINSWITH expressions.
Compound predicates with AND,OR,and NOT. Sub-queries with “key IN
%@”,subquery. See our docs for more details and examples.
分解参数的具体技巧
我建议评估任何显示如何解释REST API值的示例.请记住,大多数传输可能代表类似JSON的格式.在这些情况下,”’方括号是数组,'{‘花括号代表字典,你需要在将参数化数据推入http请求之前对其进行编码.
应用信息
采用上面讨论的内容,您可以创建REST API调用.您必须编码特定于您的用例的各种标准的where子句.可以使用以下方法确保这些参数与您需要的查询属性一致:
var encodedParam = param.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
假设上面的参数是一些字符串,其键值类似于:
'where={"$or":[{"wins":{"$gt":150}},{"wins":{"$lt":5}}]}'
编码参数将在您的Application ID和REST API密钥之后添加到基本REST-API查询字符串中 – 这应该返回您想要的对象:
(注意用于查询的第四个URL).
看起来编码的参数应该在上面引用的类名之后,如下例所示:
(使用上面的格式推断您的值,还要注意查询字符串“… classname?%s encodedParams”上的额外字符).
其他查询示例
可以通过使用Parse网站上提供的examples来推断如何构建更复杂的查询.将这些查询打包到编码参数中应该会产生您寻求的结果.我要做的是首先使用常规Parse API构造一个查询,然后将其转换为上面确定的REST-API构造.
例如:
let urlpath = NSString(format: "https://api.parse.com/1/classes/Photo?%s\(encodedParams)") ... add code to call the urlPath
对您主要问题的具体答案
在重新阅读问题之后,我想回答您需要在REST-API参数列表中添加多个子查询的特定问题.我认为仔细检查$或子句会很有用.只要您可以将Photo对象上的相关键应用于多个条件,那么您应该能够实现您的目标.
'where={"$or":[{"wins":{"$gt":150}},{"wins":{"$lt":5}}]}'
复合查询示例
$或子句是在复合查询下在Parse网站上使用的示例.上面的代码可以转换为您的用例,并使用之前指定的编码url方法应用.
Nota Bene
请注意,下面的示例显示了多个相关对象的检索(使用$inQuery).关于可以检索多少内部对象存在限制.我注意到这基本上是你在代码中做的等价,所以希望使用这个样本推断相对简单.
警告
请注意Parse关于何时使用REST-API的注意事项.