I am study about Realm db, this db is nice as compare with core data but I am stuck on one place as follows:
I have two RLMObject in that I created relationship and I want to run join query (sub query) on that, but I can't do that.
first object (table) in Ralm
class Dog : RLMObject
{
dynamic var name = ""
dynamic var age = 0
// create variable of Owner object
dynamic var owner = RLMArray(objectClassName: "Owner")
override class func primaryKey() -> String!{
return "name"
}
}
second object (table) in Ralm
class Owner : RLMObject{
dynamic var myName = ""
}
so I want to fetch only those Dog names which belong with owner name 'ram' I tried following sub query
var dog = Dog.allObjects().objectsWithPredicate(NSPredicate(format:"SUBQUERY(Owner, $owner, $owner.myName = 'ram')", argumentArray: nil))
but app is crashing with following error
RealTest[1701:17960] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "SUBQUERY(owner, $owner, $owner.myName = 'ram')"'
also I search it on net I found that realm.objects but it gave me error about not found.
Thanks in advance!
Your predicate should look like this:
let predicate = NSPredicate(format:"SUBQUERY(Owner, $owner, $owner.myName = 'ram') .@count > 0", argumentArray: nil)
The idea here is to make sure you add .@ count > 0
at the end, as the predicate needs to return true
or false
for it to work.
This can be achieved using a query like:
Dog.allObjects().objectsWhere("ANY owner.myName = 'ram'")
SUBQUERY
is only necessary if you have multiple constraints on the target of the relationship that must all be fulfilled by a single row, or if you wish to express a constraint other than ANY
/ ALL
/ NONE
on the number of rows that match.
That said, as of Realm Objective-C and Swift 0.98.0 SUBQUERY
is now supported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With