菜鸟教程小白 发表于 2022-12-11 20:52:56

ios - 如何避免在 Realm 数据库中添加具有相同主键的相同数据模型?


                                            <p><p> <a href="/image/Dhzh9.png" rel="noreferrer noopener nofollow"><img src="/image/Dhzh9.png" alt="enter image description here"/></a> </p>

<p>我在两个模型之间有一对多的关系,<code>Product</code> 和 <code>WishList</code> 就像下面的代码</p>

<pre><code>class Product : Object {

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

    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() -&gt; String? {
      return &#34;productID&#34;
    }

}
</code></pre>

<p>和愿望 list :</p>

<pre><code>class WishList : Object {
    @objc dynamic var userID: String = &#34;&#34;
    var products = List&lt;Product&gt;()
}
</code></pre>

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

<pre><code>    // 1. get the wishlist based on UserID

    let allWishList = realm.objects(WishList.self)
    let theWishList = allWishList.filter(&#34;userID CONTAINS %@&#34;, 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
      }


   }
</code></pre>

<p>这是Realm Browser中的数据
<a href="/image/EkR0T.png" rel="noreferrer noopener nofollow"><img src="/image/EkR0T.png" alt="enter image description here"/></a> </p>

<p> <a href="/image/AyvoD.png" rel="noreferrer noopener nofollow"><img src="/image/AyvoD.png" alt="enter image description here"/></a> </p>

<p>问题是......</p>

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

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

<blockquote>
<p>&#39;RLMException&#39;, reason: &#39;Attempting to create an object of type
&#39;Product&#39; with an existing primary key value &#39;a&#39;</p>
</blockquote>

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

<p>所以,我的问题是,如果 <code>Product</code> 具有相同的 productID(主键),如何避免添加,最好在添加产品时仅更新 Realm 数据库中的产品使用这行代码添加到愿望 list :<code>userWishList.products.append(selectedProduct)</code> </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您可以检查所选产品的属性<code>hasBeenAddedToWishList</code>,如果该属性为false,则仅添加它。</p>

<pre><code> if loveIconHasBeenFilled {
   //your logic to remove already added products

} else if !selectedProduct.hasBeenAddedToWishList { //&lt;--- 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
}
</code></pre>

<p>}</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 如何避免在 Realm 数据库中添加具有相同主键的相同数据模型?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/53532322/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/53532322/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 如何避免在 Realm 数据库中添加具有相同主键的相同数据模型?