【问题标题】:Realm: Can't set primary key property 'id' to existing value领域:无法将主键属性“id”设置为现有值
【发布时间】:2016-06-18 14:25:19
【问题描述】:

好的,所以我有一个 Realm 数据库(名为 AutoComplete),其结构如下

我 现在我调用后端,获取所有 [Folder] 项目。

        Alamofire.request(.GET, URL).responseObject { (response: Response<Folders, NSError>) in
            if response.result.isSuccess {
                let mappedObject = response.result.value
                let realm = try! Realm()
                // open AutoComplete model
                let openAutoComplete = realm.objects(AutoComplete)
                try! realm.write {
                    if let everythingUnderResult = mappedObject?.result {
                        // for folder in [Folder]
                        for item in everythingUnderResult {
                       //check if the search string you typed in exists in the database                            
                        let searchifExists = openAutoComplete.filter("search == %@", searchString)
                            let makeString = searchifExists.first
                            let getSearchColumn = makeString?.search
                            if searchString == getSearchColumn {
                                //item exists, now add the folder to the autocomplete DB
                                makeString?.folder.append(item)
                                realm.add(makeString!,update: true)
                            } else {
                                print(item)
                                realm.add(item)
                                makeString?.folder.append(item)
                            }
                        }
                    }
                }
            } else {
                print("couldn't get mobileapp data")
            }
        }

    }

我的问题是我无法将folderobjects 添加到数据库中。 makeString?.folder.append(item) 代码行返回以下错误:

Can't set primary key property 'id' to existing value '65502'.'

我知道该id已经存在于我的数据库Folders模型中,具有相同的ID,但我只想在Autocomplete模型中引用它。 (不要更新或覆盖它)。

有人知道如何解决这个问题吗?

【问题讨论】:

  • 您愿意分享您的模型定义,或者至少与您的代码 sn-p 相关的部分吗?

标签: ios swift realm alamofire


【解决方案1】:

在这部分代码中

   if searchString == getSearchColumn {
                            //item exists, now add the folder to the autocomplete DB
                            makeString?.folder.append(item) // it's ok
                            realm.add(makeString!,update: true) // you don't need this
                        } else {
                            print(item)
                            realm.add(item)
                            makeString?.folder.append(item)
                        }

删除

realm.add(makeString!,update: true)

这条记录不需要再添加一次到表中,添加到文件夹列表就足够了

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
相关资源
最近更新 更多