swift3 - Realm Swift select all values which match one field in one-to-many relationship entity -
i have 2 entities in realm product , producttype. product has 1 many relation product type.
product entity 1 many
import foundation import realmswift class product: object{ dynamic var productname = "" let producttypelist = list<producttype>() }
producttype entity
import foundation import realmswift class producttype: object{ dynamic var typename: string = "" dynamic var typelogourl: string = "" }
my goal select products, contains producttype typename, example "electronics". can easily, if there 1 one relationship this
product entity 1 one
import foundation import realmswift class product:object{ dynamic var productname = "" dynamic var producttype : producttype? }
query example
let realm = try! realm() let producttypename = "electronics" let predicate = nspredicate(format: "producttype.typename == %@", producttypename) let rmproducts = realm.objects(product.self).filter(predicate)
any ideas how make query 1 many version of product class?
you have use subquery , check count of producttypes in list matching name bigger 0.
let rmproducts = realm.objects(product.self).filter("subquery(producttypelist, $type, $type.typename == %@).@count>0",producttypename)
i have run query on following test set , got expected results:
class product:object{ dynamic var productname = "" var producttypelist = list<producttype>() } class producttype : object{ dynamic var typename: string = "" dynamic var typelogourl: string = "" } let types = [producttype(value: ["typename":"electronics","typelogourl":"url"]),producttype(value: ["typename":"a","typelogourl":"url"]),producttype(value: ["typename":"electronics","typelogourl":"a"]),producttype(value: ["typename":"b","typelogourl":"url"])] let prod1 = product() prod1.productname = "a" prod1.producttypelist = list([types[0],types[1]]) let prod2 = product() prod2.productname = "b" prod2.producttypelist = list([types[3],types[1]]) let prod3 = product() prod3.productname = "c" prod3.producttypelist = list([types[2],types[1]]) var prod4 = product() prod4.productname = "d" prod4.producttypelist = list([types[1]]) try! realm.write { realm.add(types) realm.add([prod1,prod2,prod3,prod4]) } let producttypename = "electronics" let predicate = nspredicate(format: "producttype.typename == %@", producttypename) let rmproducts = realm.objects(product.self).filter("subquery(producttypelist, $type, $type.typename == %@).@count>0",producttypename) print(rmproducts) //rmproducts contains prod1 , prod3 expected
Comments
Post a Comment