Search code examples
iosswiftparse-platformmerging-data

Merging Two Parse Tables in a Query


I have two parse classes, one is "users" and one is where users enter some comments like "tweets". In "users" class every object has two columns a username and a photo. In tweets table every object has the info of username and comment. I need to make a query that merges these two tables according to username matches, and finally should have 3 columns, username - photo - comment. How can I do this via swift in xcode? Than I will use the result append it as arrays and show them in table view cells.


Solution

  • You should take a look at Parse 1-many relationships. Here you can find Swift-based code snippets.

    Basically, you do not link a user's tweets to that user by associating the user name (this is what would happen in a SQL database). What you do is assigning a user object to the tweets, then when you have a tweet, you can access its user attribute and all of its properties.

    let user = PFObject(className:"TweetAuthor")
    ...
    let tweet = PFObject(className:"Tweet")
    tweet["..."] = ...
    tweet["createdBy"] = user
    ...
    let userTweets = PFQuery(className:"Tweet")
    tweetQuery.whereKey("createdBy", equalTo: user)
    tweetQuery.findObjectsInBackgroundWithBlock {
          (objects: [AnyObject]?, error: NSError?) -> Void in
    
        let aTweet = object![...]
        let picture = aTweet["createdBy"]["picture"]
        ...
    }
    

    Hope this helps.

    EDIT:

    How should you use the code above?

    I assume that at some place in your app, you create a Tweet and you currently assign it a 'username' (and 'profilePicture', etc.):

    tweet["userName"] = user["username"]
    

    Instead of assigning a userName (string), assign it the full user object:

    tweet["createdBy"] = user
    

    (remove all code to assign profilePicture, etc.)

    Once you have this, you can get the picture associated to a tweet by doing:

    let picture = aTweet["createdBy"]["picture"]