日々精進

新しく学んだことを書き留めていきます

ParseのiOS Guide抄訳4

    // whereKey:matchesKey:inQuery:でInnerJoinっぽいことができる
    // 検索結果の最大件数1000件の制限はteamQueryとuserQueryの両方にかかるので注意すること!
    PFQuery *teamQuery = [PFQuery queryWithClassName:@"Team"];
    [teamQuery whereKey:@"winPct" greaterThan:[NSNumber numberWithDouble:0.5]];
    PFQuery *userQuery = [PFQuery queryWithClassName:@"User"];
    [userQuery whereKey:@"hometown" matchesKey:@"city" inQuery:teamQuery];
    [userQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
        // 処理
    }];
    // 上記はSQLで書くとこんな感じ。ただし取得できるデータはUserのデータのみ。
    // SELECT * FROM User, Team where User.hometown = Team.city and Team.winPct > 0.5

    // 配列に2が含まれるオブジェクトが取得できる
    [query whereKey:@"arrayKey" equalTo:[NSNumber numberWithInt:2]];
    // matchesRegexでPerl互換の正規表現が使える。whereKey:matchesRegex:modifiers:のmodifiersにi(大文字小文字無視)とかm(複数行マッチ)とか使える。
    // whereKey:containsString:、whereKey:hasPrefix: 、whereKey:hasSuffix:がある

    // 特定のPFObjectに紐付くPFObjectを取得できる
    [query whereKey:@"post" equalTo:[PFObject objectWithoutDataWithClassName:@"Post" objectId:@"1zEcyElZ80"]];

    PFQuery *innerQuery = [PFQuery queryWithClassName:@"Post"];
    [innerQuery whereKeyExists:@"image"];
    PFQuery *query1 = [PFQuery queryWithClassName:@"Comment"];
    [query1 whereKey:@"post" matchesQuery:innerQuery];
    [query1 findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
        // comments now contains the comments for posts with images
    }];
    // 上記を無理矢理SQLで表現するとこんな感じ。
    // SELECT * FROM Post, Comment WHERE Post.id = Comment.post_id AND [Postがimageキーを持っている]

    // includeKeyを使うと関連するオブジェクトをまとめてとってこれる。
    [query includeKey:@"post"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
        for (PFObject *comment in comments) {
            PFObject *p = [comment objectForKey:@"post"];
            NSLog(@"retrieved related post: %@", p);
        }
    }];

    // ドットでつなぐとさらに先のオブジェクトまで取ってこれる
    [query includeKey:@"post.author"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *comments, NSError *error) {
        for (PFObject *comment in comments) {
            PFObject *p = [comment objectForKey:@"post"];
            PFObject *author = [p objectForKey:@"author"];
            NSLog(@"retrieved related post: %@", author);
        }
    }];