OGeek|极客世界-中国程序员成长平台

标题: ios - 如何避免在 Realm 数据库中添加具有相同主键的相同数据模型? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:52
标题: ios - 如何避免在 Realm 数据库中添加具有相同主键的相同数据模型?

enter image description here

我在两个模型之间有一对多的关系,ProductWishList 就像下面的代码

class Product : Object {

    @objc dynamic var productID : String = ""
    @objc dynamic var name : String = ""
    @objc dynamic var unitPrice: Double = 0.0
    @objc dynamic var imagePath : String = ""
    @objc dynamic var quantity = 0
    @objc dynamic var hasBeenAddedToWishList : Bool = false
    var parentCategory = LinkingObjects(fromType: WishList.self, property: "products")

    convenience init(productID : String, name: String, unitPrice: Double, imagePath: String, quantity: Int = 1, hasBeenAddedToWishList: Bool = false) {
        self.init()

        self.productID = productID
        self.name = name
        self.unitPrice = unitPrice
        self.imagePath = imagePath
        self.quantity = quantity
        self.hasBeenAddedToWishList = hasBeenAddedToWishList
    }

    override static func primaryKey() -> String? {
        return "productID"
    }

}

和愿望 list :

class WishList : Object {
    @objc dynamic var userID: String = ""
    var products = List<roduct>()
}

当按下上图中的爱按钮时,我尝试使用下面的代码将产品添加或删除到愿望 list :

    // 1. get the wishlist based on UserID

    let allWishList = realm.objects(WishList.self)
    let theWishList = allWishList.filter("userID CONTAINS[cd] %@", userID).first

    guard let userWishList = theWishList else {return}


    // 2. modify Wishlist data in Realm.

    if loveIconHasBeenFilled {

       guard let index = userWishList.products.index(where: {$0.productID == selectedProduct.productID}) else {return}

       do {
        // remove data from realm database            

          try realm.write {
            userWishList.products.remove(at: index)
          }

        } catch {
          // error Handling
        }



    } else {

      do {

         // add product to wishlist model in realm database

         try realm.write {
            userWishList.products.append(selectedProduct)
         }

      } catch {
        // error Handling
      }


   }

这是Realm Browser中的数据 enter image description here

enter image description here

问题是......

当我第一次运行应用程序时,我可以添加,然后删除,然后再次将产品添加到愿望 list , Realm 数据库中的产品数量仍然相同(都有唯一的产品ID)

但是当我重新启动应用程序并尝试单击那个爱按钮以再次将产品添加到愿望 list 时,它会引发错误

'RLMException', reason: 'Attempting to create an object of type 'roduct' with an existing primary key value 'a'

这个错误是因为这行代码 userWishList.products.append(selectedProduct) 触发的,添加产品到WishList时会自动添加Product 在 Realm 数据库中。因此,因为我不断添加具有相同 productID(主键)的相同产品,它会抛出该错误。

所以,我的问题是,如果 Product 具有相同的 productID(主键),如何避免添加,最好在添加产品时仅更新 Realm 数据库中的产品使用这行代码添加到愿望 list :userWishList.products.append(selectedProduct)



Best Answer-推荐答案


您可以检查所选产品的属性hasBeenAddedToWishList,如果该属性为false,则仅添加它。

 if loveIconHasBeenFilled {
   //your logic to remove already added products

} else if !selectedProduct.hasBeenAddedToWishList { //<--- check if the product already exists in wishlist if not you add it

  do {

     // add product to wishlist model in realm database

     try realm.write {
        userWishList.products.append(selectedProduct)
     }

  } catch {
    // error Handling
  }

}

关于ios - 如何避免在 Realm 数据库中添加具有相同主键的相同数据模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53532322/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4