简体   繁体   中英

How to use query result in query itself in Realm

I want to use result value in realm query. I have sqlite query example as below,

query = [NSString stringWithFormat:@"Select * from tbl_numbering_plan where np_country_code ='%@' and np_prefix = SUBSTR('%@',0,Length(np_prefix))", [dictContactDetails objectForKey:KEY_CountryCode], [dictContactDetails objectForKey:KEY_CountryCode], [dictContactDetails objectForKey:KEY_Phonenumber]];

Here is tbl_numbering_plan is table name, np_country_code and np_prefix are rows of table.

Consider the last part of query that is np_prefix = SUBSTR('%@',0,Length(np_prefix) . I want to make same query in Realm.

Here is your table tbl_numbering_plan

Define your models like regular Swift classes

class Numbering_plan: Object {
    @objc dynamic var np_country_code = ""
    @objc dynamic var np_prefix = ""
}

The last part of query that is np_prefix = SUBSTR('%@',0,Length(np_prefix) ,

Just handle it as Swift regular Substring

let dictContactDetails = [String: Any]()
let KEY_CountryCode = "KEY_CountryCode"
let KEY_Phonenumber = "KEY_Phonenumber"
let np_prefix = "np_prefix"
if let code = dictContactDetails[KEY_CountryCode] as? String, var phone = dictContactDetails[KEY_Phonenumber] as? String{
      let index = phone.index(phone.startIndex, offsetBy: np_prefix.count)
      phone = String(phone[..<index])
      let result = realm.objects(Numbering_plan.self).filter("np_country_code = '\(code)' AND np_prefix = '\(phone)'")
      print(result)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM