在我的API上,我拥有Stands和Products之间的关系。在哪些展位中有产品,但也可以在不同的展位中找到产品。我正在尝试使用Realm在我的iOS应用程序上复制这种关系,但似乎无法正常工作。
建立这种关系的目的是能够搜索出售特定产品的展台。
我的模特:
class Stand: Object {
dynamic var id : Int = 0
dynamic var name : String = ""
dynamic var latitude : Double = 0.0
dynamic var longitude : Double = 0.0
let products = List<Product>()
override static func primaryKey() -> String? {
return "id"
}
}
class Product: Object {
dynamic var id : Int = 0
dynamic var name : String = ""
let stands = List<Stand>()
override static func primaryKey() -> String? {
return "id"
}
}
Run Code Online (Sandbox Code Playgroud)
当执行我的Stands API请求时,我也会同时检索关联的产品。当我将这些附加到Stands上时,它对于我的Stands模型非常有效,因为产品通常只是添加到List()中。
但是所有产品都是单独创建的,没有附加任何支架。
创建产品后,是否可以将这些支架直接分配给产品?就像发生了另一种情况一样?
我当前的解决方案是
func retrieveAndCacheStands(clearDatabase clearDatabase: Bool?) {
backend.retrievePath(endpoint.StandsIndex, completion: { (response) -> () in
let listOfProducts : List<(Product)> = List<(Product)>()
func addProducts(stand: Stand, products: List<(Product)>?) {
for product in products! {
print(product.name)
let newProduct = Product()
newProduct.id = product.id
newProduct.name = product.name
newProduct.stands.append(stand)
try! self.realm.write({ () -> Void in
self.realm.create(Product.self, value: newProduct, update: true)
})
}
listOfProducts.removeAll()
}
for (_, value) in response {
let stand = Stand()
stand.id = value["id"].intValue
stand.name = value["name"].string!
stand.latitude = value["latitude"].double!
stand.longitude = value["longitude"].double!
for (_, products) in value["products"] {
let product = Product()
product.id = products["id"].intValue
product.name = products["name"].string!
stand.products.append(product)
listOfProducts.append(product)
}
try! self.realm.write({ () -> Void in
self.realm.create(Stand.self, value: stand, update: true)
})
addProducts(stand, products: listOfProducts)
}
print(Realm.Configuration.defaultConfiguration.path!)
}) { (error) -> () in
print(error)
}
}
Run Code Online (Sandbox Code Playgroud)
这将存储支架并将产品添加到其中。它还会创建所有产品,并每10 ish产品(?)添加1个Stand。
我似乎无法弄清楚如何进行这项工作。有谁知道如何解决这个问题?还是更好的解决方案?
您应该使用Realm的逆向关系机制来代替手动维护逆向关系所需的双重簿记,该机制使用给定的属性为您提供指向另一个对象的所有对象:
class Product: Object {
dynamic var id: Int = 0
dynamic var name: String = ""
// Realm doesn't persist this property because it is of type `LinkingObjects`
// Define "stands" as the inverse relationship to Stand.products
let stands = LinkingObjects(fromType: Stand.self, property: "products")
override static func primaryKey() -> String? {
return "id"
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参见Realm关于逆向关系的文档。