So, I have a query in parse that has to find objects based on whether a key is equal to a certain object. Here is the few lines of code.
var gamesQuery = PFQuery(className: "Games")
gamesQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))
gamesQuery.whereKey("challenger", equalTo: PFUser.currentUser()!)
However, when this query is ran, the query is occasionally found as nil due to the fact that there is no object that fits the search parameters.
Is there any check that I could run that could check if
gamesQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))
is nil? Any help with this issue would be very appreciated.
Your current query is essentially an and - "find objects where challenged==current user and challenger==current user".
I think you are after an or query - "find objects where challenged==current user or challenger==current user". You can do this with a compound query in Parse -
let challengedQuery = PFQuery(className: "Games")
challengedQuery.whereKey("challenged", equalTo: (PFUser.currentUser()!.objectId!))
let challengerQuery = PFQuery(className: "Games")
challengerQuery.whereKey("challenger", equalTo: PFUser.currentUser()!)
let gamesQuery = PFQuery.orQueryWithSubqueries([challengedQuery, challengerQuery])
gamesQuery.findObjectsInBackgroundWithBlock {
(results: [PFObject]?, error: NSError?) -> Void in
if error == nil {
// results contains challenger and challenged games.
}
}
Related
I have a Parse Class named friendRequest where keys are requestFrom & requestTo which contains unique ids of people who have sent request and received them respectively.
I have a user for whom I need to fetch friend requests which have been sent to him and received by him to find out the status of the request.
I am trying to combine two queries where I match the user's id in requestFrom & requestTo keys and fetch all the results where the condition is true. I get 0 values in return.
My code is:
let friendsQuery : PFQuery = PFQuery(className: "friendRequest")
let objectId = PFUser.current()?.objectId
friendsQuery.whereKey("requestFrom", equalTo: objectId!)
friendsQuery.whereKey("requestTo", equalTo: objectId!)
friendsQuery.findObjectsInBackground(block: { (objects, error) in
//code
})
How should I combine the queries to get the desired results?
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.
I have did a lot of querys, searched in websites , And already asked this question before and i didn't found a good answer!
I have Parse backend looks like this:
In my view controller I just want to show Last createdAt for each sender
i want to get all the row of last object for sender:.
so we should ignore "name1: Hello" and "name2: Really when was.." because this old rows we already got new objects.
I want one result for each sender depends on createdAt
so can I get help with query to do this? or how can we do that?
let query = PFQuery(className: "test")
query.whereKey("receivers", equalTo: PFUser.currentUser()!.username!)
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
(objects, error) -> Void in
if error == nil {
// now what? I've done everything i could none worked fine
I hope if i'll get a help to do that, So please help me if you could.
you can just add a limit to the query.. see parse docs..
let query = PFQuery(className: "test")
query.whereKey("receivers", equalTo: PFUser.currentUser()!.username!)
query.orderByDescending("createdAt")
query.limit = 1
query.findObjectsInBackgroundWithBlock {
(objects, error) -> Void in
if error == nil {
Your data model isn't really suitable for doing this operation quickly. But, how you setup your data model is dictated by all of your requirements, not just one.
To make this easy you should add a pointer from your User to your Message, and every time a message is sent by a user you set that pointer (which replaces the old pointer).
Now, you can simply query Users, using includeKey to get the message, and display your list.
I'm trying to query my User table with the Users objectId queried from another table.
Here's my code:
func queryFriendsTable() {
var queryFriends = PFQuery(className: "Activity")
queryFriends.whereKey("type", equalTo: "friend")
queryFriends.whereKey("fromUser", equalTo: PFUser.currentUser()!)
queryFriends.includeKey("toUser")
var queryUserTable = PFUser.query()
queryUserTable!.whereKey("objectId", matchesKey: "toUser", inQuery: queryFriends)
queryUserTable!.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
self.friendNamesArray.addObject(object["username"]!)
println(self.friendNamesArray)
}
}
}
}
}
Nothing is being returned when I run this query. I think the problem has to do with the fact that the toUser objectId in the Activity table is a pointer and not a string. (The toUser value I try to use in the matchesKey spot is a pointer)
So how can I get the objectId as a string from a pointer object using the inQuery method?
Your suspicions are correct. Parse won't find pointers when looking through the User's class. Instead what you'll need to do is create a string variable and set it equal to the result of queryFriends. So what that means is you'll have to run that query first, get the pointer back, and access it's objectId field as a string in order to use it in your following query.
I am still having problems understanding the correct way of handling deeper pointer structure in parse.
Example:
Card has pointer to CardSet
CardSet has pointers to Lesson and User
Lets say, I want to have all CardSets including
Lesson.name
Count of Cards for each CardSet
Can I query all this in just one query?
And have the data available without any additional fetchIfNeededInBackgroundWithBlock queries?
I know that I can get the Lesson with
var query = PFQuery(className: "CardSet")
query.whereKey("user", equalTo: PFUser.currentUser())
query.includeKey("lesson")
But that gives me only the lesson object, I can not access any data (like the col "name") from this class unless I use fetchIfNeededInBackgroundWithBlock what takes another query and of course more time to load.
What can I do to have all queried data
including all pointers columns
in order to pin this data to the local datastore with
PFObject.pinAllInBackground(objects, block: nil)
And not to forget, how can I query the number of cards related to the CardSet?
First I would recommend subclassing in Parse, it makes relationships between tables (pointers etc) clearer.
How to subclass the PFObjects you can explore this guide on parse
How to query the number of cards in CardSet
You need the CardSet from which you want the cards. (PFObject or subclassed PFObject).
Then just do this:
var query = PFQuery(classname: "cards")
query.whereKey("CardSet", equalTo: yourCardSetObject)
//Synchronously
query.findObjects().count
//Asynchronously
query.findObjectsInBackgroundWithBlock({
(objects, error) in
if error != nil {
println(error.localizedDescription)
return
}
objects.count
})
How to get the name of the lesson
As I said, it's recommended to subclass the PFObjects because you need to cast the objects what isn't really funny to debug and is horrible code.
I did it that way:
var query = PFQuery(className: "CardSet")
query.whereKey("user", equalTo: PFUser.currentUser())
query.includeKey("lesson")
query.findObjectsInBackgroundWithBlock({
(objects, error) in
if error != nil {
println(error.localizedDescription)
return
}
for object in objects as? [PFObject] {
var lesson = object["lesson"] as PFObject
println(lesson["name"])
}
})