Parse - Many to One Query - ios

I have a query that gets latest posts by users. Each post has an "Owner" field that has the "ObjectId" of the account that created it. I do this because I want to also display the username of the person who created the post - which is found in the User table.
I looked at the Parse documentation for Queries and came up with this (modeled after one of their examples):
var query = PFQuery(className:"Post")
query.orderByDescending("createdAt");
var innerQuery = PFQuery(className: "User")
innerQuery.whereKey("objectId", matchesQuery: query)
Then I run the findObjectsInBackgroundWithBlock. I don't think I'm getting the information from the User table to get the name of the person who posted the post.
I looked at the object that contains the information for the post but I don't see the information for the user in that object. What am I doing wrong?
Here are screenshots of the headers of my two tables:
POST:
USER:
Thanks!

I think the problem as that you refer to the user table in the query as "PFQuery(className: "User")". But if you use the built in user table, it's name is actually "_User". So use that, or even simplier, use:
var innerQuery = PFUser.query()

Try this
var class = PFQuery(className:"Post")
var finduser:PFQuery = PFUser.query()
finduser.whereKey("objectId", equalTo: class.objectForKey("owner").objectId)
finduser.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]!, error:NSError!)->Void in
if (error == nil){
if let userObjects = objects {
let UserResult = (userObjects as NSArray).lastObject as? PFUser
if let user = UserResult {
println(user.username)
}
}
}
}

Related

using a friend system in ios parse swift

I created a query with subquery
var userInitiated = PFQuery(className: "friends")
userInitiated.whereKey("friender", equalTo: PFUser.currentUser()!.username!)
var friendInitiated = PFQuery(className: "friends")
friendInitiated.whereKey("friendee", equalTo: PFUser.currentUser()!.username!)
// find friends of user
let friendQuery = PFQuery.orQueryWithSubqueries([userInitiated, friendInitiated])
friendQuery.findObjectsInBackgroundWithBlock ({ (objects:[PFObject]?, error:NSError?) in
if error == nil {
// cleanup
self.friendArray.removeAll(keepCapacity: false)
// STEP 2 Hold Recieved Data
// find objects that you queried for
for object in objects! {
self.friendArray.append(object.valueForKey("-----") as! String)
}
}
})
In the for object in objects part - I want to append the usernames that I got from the query but I only want to add the ones that aren't the current users username, how would I do that?
A is current User, B is one of A's friends. So what the (friender, friendee) pair in your "friends" class?
Both (A,B), (B,A)
one of (A,B) and (B,A)
In first case, you can just query friender equalTo currentUser
In second case, your query seems ok.

Two constraints on one key in a Parse Query

I'm using Parse and my app is written in Swift. I have a golf app that allows a user to friend other users. The users can log their golf scores and then see their golf scores and their friend's scores in a leaderboard style tableViewController.
The problem I'm having is that Parse doesn't support two constraints on the same key in a query. I have a function that queries the users and their scores and stores them in an array of tuples (leadeboardData). I'm trying to querying the current user's PFRelation as well as the current user (variable "friendsRelation" and constant "friendQuery"). The class I query is the "GolfScorecard", which is where the scores are stored on Parse. I then called the "whereKey" method on the "golfer" key, which is where my user is stored under on Parse. I call "whereKey matchesQuery" for my friendsRelation query and then "whereKey equalTo" to try and get my current user. I then "includeKey" "golfer" so I can get the user info along with the score info. Any suggestions on how to go about this? I'm trying to do it all in one query but when the "whereKey" method is called on the same key ("golfer") the last one overrides the first one, which makes it only possible to get the friend info or the current user info but not both. I'm stumped how to include both. Thanks in advance.
Here is my function I call to make the query:
func loadLeaderboardData() {
leaderboardData.removeAll()
friendsRelation = PFUser.currentUser()?.objectForKey("friendsRelation") as? PFRelation
friendsRelation = PFUser.currentUser()?.objectForKey("friendsRelation") as? PFRelation
let friendQuery = friendsRelation?.query()
let query = PFQuery(className: "GolfScorecard")
query.whereKey("golfer", matchesQuery: friendQuery!)
query.whereKey("golfer", equalTo: PFUser.currentUser()!)
query.includeKey("golfer")
query.orderByAscending("score")
query.findObjectsInBackgroundWithBlock { (scoreCards: [PFObject]?, error: NSError?) -> Void in
if error == nil {
for object:PFObject in scoreCards! {
let golfer:PFObject = object["golfer"] as! PFObject
self.leaderboardData.append(object,golfer)
dispatch_async(dispatch_get_main_queue()) {
self.leaderboardTableView.reloadData()
}
}
} else {
print(error)
}
}
}
Thanks Paulw11 the orQueryWithSubQueries worked. The only issue it ended up presenting was my app was crashing with an error stating 'Key "username" has no data. Call fetchIfNeeded before getting its value.'...I don't think the Parse Query was coming back in time to load in the tableView that I was putting the data in. I ended up using the 'fetchIfNeededInBackgroundWithBlock' method inside of the cellForRowAtIndexPath call around the code where I was calling the 'username' data at. This allowed it to grab the data in the background if it didn't come back in time. This seemed to due the trick.
-Also I subclassed my queries, which is where the GolfScorecard & GolferProfile is coming from inside of my for-in loop.
-This is my new compound Query:
func loadLeaderboardData() {
leaderboardData.removeAll()
friendsRelation = PFUser.currentUser()?.objectForKey("friendsRelation") as? PFRelation
let friendQuery = friendsRelation?.query()
let friendScorecardQuery = PFQuery(className: "GolfScorecard")
friendScorecardQuery.whereKey("golfer", matchesQuery: friendQuery!)
let currentUserScorecardQuery = PFQuery(className: "GolfScorecard")
currentUserScorecardQuery.whereKey("golfer", equalTo: PFUser.currentUser()!)
let subQuery = PFQuery.orQueryWithSubqueries([friendScorecardQuery, currentUserScorecardQuery])
subQuery.orderByAscending("score")
subQuery.findObjectsInBackgroundWithBlock { (scoreCards: [PFObject]?, error: NSError?) -> Void in
if error == nil {
for object:PFObject in scoreCards! {
if let object = object as? GolfScorecard {
let golfer = object["golfer"] as! GolferProfile
self.leaderboardData.append(object,golfer)
dispatch_async(dispatch_get_main_queue()) {
self.leaderboardTableView.reloadData()
}
}
}
} else {
print(error)
}
}
}

How to store retrieved data to the another class in Parse

I've a small problem. I am working on an App using Parse backend. So my problem is:
i've retrieved all the objectIds of users in _User class like this:
var userIds = [String]()
var userQuery = PFUser.query()
userQuery?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
self.userIds.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
if user.objectId != PFUser.currentUser()?.objectId {
self.userIds.append(user.objectId!)
}
}
}
}
println(userIds)
})
Now i want to save all the userIds which are stored in the array "userIds" to a column in a class named "Something". so the code will be like:
var something:PFObject = PFObject(className: "Something")
something["users"] = // have problem here
something.saveInBackground()
if i put userIds here, it gives an error.. because userIds is an array but column "users" is String.. but also i want to save all the userIds seperately in the column "users" like it is saved in objectId column of _User class..
I'm new here and I can't comment in the reply where you asked for help. Anyway, what do you want now is save only new users, as you said:
I just want to save the users which are not there
Well, there are some suggestions:
You can retrieve your User class and check for new users manually in the app and then send the new ones to your Class.
You can create a new column in your User class like "saved" where contains a boolean indicating if you already saved this user to your custom class or not. Remember also, of always do
user["saved"] = false
while creating a new user and then simply do:
let search = PFQuery(className: "_User")
search.whereKey("saved", equalTo: false)
to get these non saved users.
I strongly recommend the second option.
Ok, the case that you describe should look something like this:
var userIds = [String]()
var userQuery = PFUser.query()
userQuery?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects as? [PFUser] {
var somethingObjects = [PFObject]()
self.userIds.removeAll(keepCapacity: true)
for user in users {
if user.objectId != PFUser.currentUser()?.objectId {
self.userIds.append(user.objectId!) // I don't know if this is necessary anymore for your usecase
var something:PFObject = PFObject(className: "Something")
something["users"] = user.objectId
somethingObjects.append(something)
}
}
PFObject.saveAllInBackground(somethingObjects)
}
})
In this case, you create a number of something objects that are saved, but you might want to rename the "users" column to "user", since you only save one objectId per row.
I haven't worked with parse in a while, so there might be a way to optimize the number of API calls you have to make.

Parse.com PFUser Query based on results from PFObject query

I have a chatroom class containing users. I can successfully query that class and return only specific PFUsers.
// get all room IDs associated with current user
var outerRoomQuery = PFQuery(className:Parse.CHATROOM_CLASS_NAME)
outerRoomQuery.whereKey(Parse.CHATROOM_USER, equalTo: PFUser.currentUser()!)
outerRoomQuery.selectKeys([Parse.CHATROOM_ROOMID])
// get all users associated with above roomIds ignoring current User
var innerRoomQuery = PFQuery(className:Parse.CHATROOM_CLASS_NAME)
innerRoomQuery.whereKey(Parse.CHATROOM_ROOMID, matchesKey:Parse.CHATROOM_ROOMID, inQuery: outerRoomQuery)
innerRoomQuery.whereKey(Parse.CHATROOM_USER, notEqualTo: PFUser.currentUser()!)
innerRoomQuery.includeKey(Parse.CHATROOM_USER)
innerRoomQuery.orderByDescending(Parse.CHATROOM_UPDATEDACTION)
innerRoomQuery.selectKeys([Parse.CHATROOM_USER])
The above query returns about 5 users.
I'm wondering if it is possible to combine these results with a separate PFUser.query() to create an OR query something like this:
var userQuery = PFUser.query()
userQuery?.whereKey(Parse.CHATROOM_USER, matchesKey:Parse.CHATROOM_USER, inQuery: innerRoomQuery) // returns nil
var receptionQuery = PFUser.query()
receptionQuery?.whereKey(Parse.USER_ROLE, equalTo:Parse.PFROLE_RECEPTIONIST) // returns around 10 receptionist users
var orUserQuery = PFUser.query()
return PFQuery.orQueryWithSubqueries([userQuery!, receptionQuery!])
The result of above only returns the receptionists. So my question is how to achieve this line:
userQuery?.whereKey(Parse.CHATROOM_USER, matchesKey:Parse.CHATROOM_USER, inQuery: innerRoomQuery)
I know this is wrong because there is no "user" (Parse.CHATROOM_USER) field in the PFUser class. I'm just wondering if there is a way to do this without firing off the roomQuery first and putting the returned PFUsers into an array and then firing the receptionist users query and combining the arrays.
Any ideas?
I'm not entirely sure what you are asking but if you are trying to have a single query find a specific type of user, i would approach this in a different fashion. I would add a bool type to the user class for what I am searching for, and just query for all the users with that bool type as true!

Access pointer value in Parse.com object with swift

I'm trying to access the "objectId" field in "User" table, while running a query on a "Photos" table.
Here is the Parse.com query (simplified) run on "Photos" table:
func checkDbForNewPhotos() {
var query = PFQuery(className:"Photos")
query.whereKey("fbId", equalTo:"34343434343434")
query.includeKey("user.objectId"); // Is this what is needed to access user info ?
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
println(object) // See sample object below
println(user.objectId) // Error here: user type doesn't have member objectId
}
println(object): Here is a sample object returned from the query. I'm trying to access 9wEGRWSnTk from the "user" field which is a pointer to another table.
<Photos: 0x7c091fd0, objectId: 6D0aHreHsC, localId: (null)> {
alerts = 0;
country1 = france;
country2 = "";
imageFile = "<PFFile: 0x7b7d9130>";
user = "<PFUser: 0x7b7d95f0, objectId: 9wEGRWSnTk>";
}
How should I format that in swift to access 9wEGRWSnTk ?
I had the same problem. You need to cast it to a PFUser and then access the information.
let pfObject:PFObject = object as PFObject
let userObject:PFUser = pfObject["user"] as PFUser
print("User \(userObject.objectId)")
You should use
println(object["user"].objectId)
if the column where you store your user named as "user".
You could also just say EqualTo and use the PFUser.currentuser()
that way you load everything from that user only
else try to explain why you need the objectId when querying
query.whereKey("user", equalTo: PFUser.currentUser())

Resources