How to avoid adding the same data model that has the same primary key in realm database?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















enter image description here



I have one to many relationship between two models, Product and WishList like the code below



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

}


and WishList:



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


I try to add or remove product to WishList using the code below when love button in the image above is pressed :



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


}


and here is the data in Realm Browser
enter image description here



enter image description here



and the problem is ....



when I run the app for the first time, I can add, and then remove, and then add the product again to the wishlist, and the number of product in the realm database still be the same (all have unique productID)



but when I restart the app, and try to click that love button to add the product to wishlist again, it throws an error




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




this error is triggered because of this line of code userWishList.products.append(selectedProduct) , when adding the product to WishList, it automatically adds Product in the realm database. so because I keep adding the same product that has the same productID (primary key) it will throw that error.



so, my question is, how to avoid addition in Product if it has the same productID (primary key), it is better if i can just update the product in realm database when adding the product to the wishlist using this line of code: userWishList.products.append(selectedProduct)










share|improve this question























  • maybe you can consider creating another realm object to save the relation between Product and WishList

    – koropok
    Nov 29 '18 at 7:40


















2















enter image description here



I have one to many relationship between two models, Product and WishList like the code below



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

}


and WishList:



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


I try to add or remove product to WishList using the code below when love button in the image above is pressed :



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


}


and here is the data in Realm Browser
enter image description here



enter image description here



and the problem is ....



when I run the app for the first time, I can add, and then remove, and then add the product again to the wishlist, and the number of product in the realm database still be the same (all have unique productID)



but when I restart the app, and try to click that love button to add the product to wishlist again, it throws an error




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




this error is triggered because of this line of code userWishList.products.append(selectedProduct) , when adding the product to WishList, it automatically adds Product in the realm database. so because I keep adding the same product that has the same productID (primary key) it will throw that error.



so, my question is, how to avoid addition in Product if it has the same productID (primary key), it is better if i can just update the product in realm database when adding the product to the wishlist using this line of code: userWishList.products.append(selectedProduct)










share|improve this question























  • maybe you can consider creating another realm object to save the relation between Product and WishList

    – koropok
    Nov 29 '18 at 7:40














2












2








2








enter image description here



I have one to many relationship between two models, Product and WishList like the code below



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

}


and WishList:



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


I try to add or remove product to WishList using the code below when love button in the image above is pressed :



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


}


and here is the data in Realm Browser
enter image description here



enter image description here



and the problem is ....



when I run the app for the first time, I can add, and then remove, and then add the product again to the wishlist, and the number of product in the realm database still be the same (all have unique productID)



but when I restart the app, and try to click that love button to add the product to wishlist again, it throws an error




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




this error is triggered because of this line of code userWishList.products.append(selectedProduct) , when adding the product to WishList, it automatically adds Product in the realm database. so because I keep adding the same product that has the same productID (primary key) it will throw that error.



so, my question is, how to avoid addition in Product if it has the same productID (primary key), it is better if i can just update the product in realm database when adding the product to the wishlist using this line of code: userWishList.products.append(selectedProduct)










share|improve this question














enter image description here



I have one to many relationship between two models, Product and WishList like the code below



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

}


and WishList:



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


I try to add or remove product to WishList using the code below when love button in the image above is pressed :



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


}


and here is the data in Realm Browser
enter image description here



enter image description here



and the problem is ....



when I run the app for the first time, I can add, and then remove, and then add the product again to the wishlist, and the number of product in the realm database still be the same (all have unique productID)



but when I restart the app, and try to click that love button to add the product to wishlist again, it throws an error




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




this error is triggered because of this line of code userWishList.products.append(selectedProduct) , when adding the product to WishList, it automatically adds Product in the realm database. so because I keep adding the same product that has the same productID (primary key) it will throw that error.



so, my question is, how to avoid addition in Product if it has the same productID (primary key), it is better if i can just update the product in realm database when adding the product to the wishlist using this line of code: userWishList.products.append(selectedProduct)







ios swift realm






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 29 '18 at 5:19









sarahsarah

550214




550214













  • maybe you can consider creating another realm object to save the relation between Product and WishList

    – koropok
    Nov 29 '18 at 7:40



















  • maybe you can consider creating another realm object to save the relation between Product and WishList

    – koropok
    Nov 29 '18 at 7:40

















maybe you can consider creating another realm object to save the relation between Product and WishList

– koropok
Nov 29 '18 at 7:40





maybe you can consider creating another realm object to save the relation between Product and WishList

– koropok
Nov 29 '18 at 7:40












1 Answer
1






active

oldest

votes


















0














You could check the property hasBeenAddedToWishList of the selected product and only add it if the property is 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
}


}






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53532322%2fhow-to-avoid-adding-the-same-data-model-that-has-the-same-primary-key-in-realm-d%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You could check the property hasBeenAddedToWishList of the selected product and only add it if the property is 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
    }


    }






    share|improve this answer




























      0














      You could check the property hasBeenAddedToWishList of the selected product and only add it if the property is 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
      }


      }






      share|improve this answer


























        0












        0








        0







        You could check the property hasBeenAddedToWishList of the selected product and only add it if the property is 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
        }


        }






        share|improve this answer













        You could check the property hasBeenAddedToWishList of the selected product and only add it if the property is 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
        }


        }







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 29 '18 at 9:58









        LoVoLoVo

        1,2731017




        1,2731017
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53532322%2fhow-to-avoid-adding-the-same-data-model-that-has-the-same-primary-key-in-realm-d%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks