Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm how to write subquery

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. enter image description here

Thanks in advance!

like image 217
Pravin Tate Avatar asked Sep 25 '15 05:09

Pravin Tate


2 Answers

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.

like image 133
Sir Wellington Avatar answered Oct 16 '22 21:10

Sir Wellington


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.

like image 20
bdash Avatar answered Oct 16 '22 19:10

bdash