如何避免许多在加的境界数据库相同的数据一对多的关系?(how to avoid adding the

2019-11-05 08:46发布

我有wishlistVC有像下面的图片集的观点:

我有产品型号境界是这样的:

class Product : Object {

    @objc dynamic var productID : String = ""
    @objc dynamic var name : String = ""
    @objc dynamic var unitPrice: Double = 0.0
    @objc dynamic var quantity = 0
    @objc dynamic var descriptionProduct : String = ""
    @objc dynamic var hasBeenAddedToWishList : Bool = false
    @objc dynamic var hasBeenAddedToCart : Bool = false
    @objc dynamic var isNewProduct : Bool = false
    var imagePaths = List<String>()
}

和愿望清单领域模型是这样的:

    class WishList : Object {
        @objc dynamic var userID: String = ""
        var products = List<Product>() // many to many relationship

   static func getWishListFromRealmDatabase() -> WishList {

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


        if let userWishList = theWishList {
            return userWishList
        } else {
            // WishList never setted up before in Realm database container
            // then create WishList in realm database

            let newWishList = WishList()
            newWishList.userID = userID
            newWishList.products = List<Product>()
            RealmService.shared.save(object: newWishList)
            return newWishList
        }
    }


    static func addProductToWishListRealmDatabase(userWishList: WishList, selectedProduct: Product) {

        // to check wheter the selected product from user is already in WishList or not
        if userWishList.products.filter("productID == %@", selectedProduct.productID).first == nil {

            RealmService.shared.save(expression: {
                selectedProduct.hasBeenAddedToWishList = true
                userWishList.products.append(selectedProduct)
            })

        }


    }

     }

当用户轻敲爱按钮,下面是用于商品加入收藏的代码:

func addProductToWishListRealmDatabase(userWishList: WishList, selectedProduct: Product) {

        // to check wheter the selected product from user is already in WishList.products or not
        if userWishList.products.filter("productID == %@", selectedProduct.productID).first == nil {

            // write in realm database
            RealmService.shared.save(expression: { // <-- this is just a wrapper to avoid write do try catch block all over the place

                selectedProduct.hasBeenAddedToWishList = true
                userWishList.products.append(selectedProduct)


            })

        }


    }

这里是我WishListVC充分简化代码:

class WishListVC : UIViewController {

    @IBOutlet weak var wishListCollectionView: UICollectionView!

    private var userWishList : WishList?
    private var products = List<Product>()
    private var selectedProduct : Product?

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        userWishList = WishList.getWishListFromRealmDatabase() // the definition is in the code above
        guard let userWishList = userWishList else {return}
        products = userWishList.products

    }



}

extension WishListVC : ListProductCellDelegate {

    func likeButtonDidTapped(at selectedIndexPath: IndexPath, productHasBeenLiked: Bool, collectionView: UICollectionView) {

        guard let userWishList = userWishList else {return}
        let selectedProduct = products[selectedIndexPath.item]

        if productHasBeenLiked {
            WishList.removeProductFromWishListRealmDatabase(userWishList: userWishList, selectedProduct: selectedProduct)
        } else {
            WishList.addProductToWishListRealmDatabase(userWishList: userWishList, selectedProduct: selectedProduct)
        }

        wishListCollectionView.reloadData()
        self.wishListCollectionView.isHidden = userWishList.products.isEmpty

    }

}

如果我追加产品的wishlist model类似上面的代码,它会影响到Product.self的境界数据库,它会继续增加在“产品领域的数据库”的产品,你可以下面的图片看到,有9个数据产品,但你可以看到一些产品具有相同的productID,存在具有“A”作为产品ID 3种款产品。

所以如何避免补充说,在“产品领域数据库”(Product.self),当我修改相同productId使用产品的WishList通过附加产品wishlist.products?

我也试图通过添加主键:

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

但它与消息崩溃:

***终止应用程序由于未捕获的异常“RLMException”,原因:“试图创建类型的对象‘产品’与现有主密钥值‘a’。”

它会抛出错误,因为我想补充的productID =“A”

我该怎么办 ? 如何追加产品的愿望清单模型,但我也能避免增加具有相同的productID到商品领域的数据库模型(Product.self)相同的产品?

我用了错误的方式将产品添加到心愿?

文章来源: how to avoid adding the same data in Realm database in many to many relationship?
标签: ios swift realm