领域:无法将主键属性“id”设置为现有值

时间:2016-06-18 14:25:20

标签: ios swift realm alamofire

好的,我有一个具有以下结构的Realm数据库(名为AutoComplete

enter image description here

我 现在我打电话给后端,获取所有[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")
            }
        }

    }

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

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

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

任何人都知道如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

在这段代码中

   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)

您不需要再次将此记录添加到表中。将其添加到文件夹列表就足够了