领域,快速,多对多关系 [英] Realm, Swift, Many-to-many relationship

查看:51
本文介绍了领域,快速,多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的API上,支架和产品之间存在联系.在哪些展位中有产品,但也可以在不同的展位中找到产品.我正在尝试使用Realm在我的iOS应用程序上复制这种关系,但似乎无法正常工作.

On my API I've got a relationship between Stands and Products. In which stands have products, but products can be found in different stands aswell. I'm trying to replicate this relationship on my iOS-application, using Realm but I can't seem to get it working.

建立这种关系的目的是能够搜索出售特定产品的展台.

The goal of having this relationship is being able to search for Stands that sell particular products.

我的模特:

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"
    }
}

在执行我的Stands API请求时,我也会同时检索关联的产品.当我将这些附加到Stands上时,它对于我的Stands模型非常有效,因为产品通常只是添加到List()中.

When doing my API request for Stands I retrieve the associated Products with it aswell. When I append these to the Stands it works fine for my Stands model as the products are just normally added in the List().

但是所有产品都是单独创建的,没有附加任何支架.

But all of the products are individually created, without having any Stands attached to them.

是否有办法在创建产品时将这些架子直接分配给产品?就像发生了其他情况一样?

Is there a way to directly assign these Stands to the Products upon creation of the Products? Just like it's happening the other way around?

我当前的解决方案是这个.

My current solution is this..

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)
    }
}

这将存储支架并将产品添加到其中.它还会创建所有产品,并每10 ish产品(?)添加1个Stand.

This stores the Stands and adds Products to them. It also creates all the products and adds 1 Stand per 10 ish Products (?).

我似乎无法弄清楚如何进行这项工作.还有其他人知道如何解决这个问题吗?还是更好的解决方案?

I can't seem to figure out how to make this work. Does anyone else know how to solve this? Or a better solution?

推荐答案

您应该使用Realm的逆向关系机制,而不是手动维护逆向关系,而要进行两次簿记,该机制为您提供指向另一个对象的所有对象.使用给定属性的对象:

Instead of doing the double-bookkeeping necessary to maintain inverse relationships manually, you should use Realm's inverse relationships mechanism, which provides you with all of the objects pointing to another object using a given property:

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"
    }
}

有关更多信息,请参见逆关系上的Realm文档.

See Realm's docs on Inverse Relationships for more information.

这篇关于领域,快速,多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆