Deleting with one-to-many relationship

时间:2015-09-01 22:17:07

标签: swift realm

I have a one-to-many relationship:

class GameSystem: Object {
dynamic var gameSystemName = ""
}

class games: Object {
dynamic var gameSystemName = gameSystemName().name
dynamic var gameTitle = ""
dynamic var gameGenre = ""
}

The gameSystemNames are currently displayed on a TableView. If the user deletes a gameSystemName, I want that gameSystemName along with all of that system's games deleted.

The code I'm currently using will only delete the GameSystem, but leaves all the games.

    func deleteRowAtIndexPath(indexPath: NSIndexPath) {
    let realm = Realm()
    let objectToDelete = gameSystems[indexPath.row]
    realm.write {
        realm.delete(objectToDelete)
    }
    gameSystemTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    gameSystems = Realm(path: Realm.defaultPath).objects(GameSystem)
}

I'm assuming there's a simple way to do this.

2 个答案:

答案 0 :(得分:6)

如果保持模型不变,解决方案是首先查询关系Game的相关对象:

// …
let objectToDelete = gameSystems[indexPath.row]
let gameSystemName = objectToDelete.gameSystemName
realm.write {
    let games = realm.objects(Game).filter("gameSystemName = ?", gameSystemName)
    realm.delete(games)
    realm.delete(objectToDelete)
}
// …

模型建议

我建议您在模型中添加显式链接,而不是通过松散链接的外键表达关系。但是对象映射非常个性化,并且可能依赖于超出问题范围和此答案的进一步约束。如需进一步参考,如下所示:

 class GameSystem : Object {
      dynamic var name = ""
      let games = List<Game>()
 }

 class Game : Object {
      dynamic var title = ""
      dynamic var genre = ""

      // Use a backlink
      // (https://realm.io/docs/swift/latest/#inverse-relationships)
      dynamic var gameSystem: GameSystem? {
           return linkingObjects(GameSystem.self, forProperty: "games").first
      }
 }

如果你设置这样的模型,你可以很容易地删除你的游戏:

// …
let objectToDelete = gameSystems[indexPath.row]
realm.write {
    realm.delete(objectToDelete.games)
    realm.delete(objectToDelete)
}
// …

注意:将来,Realm会将Cascading Deletes作为功能。一旦发布,您甚至不需要手动删除相关游戏,但您宁愿能够在模型中声明强关系,以便自动删除游戏。

替代链接声明

您也可以声明您的链接,反之亦然,但这将使得将来使用Cascading Deletes等功能变得更加困难。但是,现在删除它们的代码与上面的代码相同。

 class GameSystem : Object {
      dynamic var name = ""

      // Use a backlink
      // (https://realm.io/docs/swift/latest/#inverse-relationships)
      dynamic var games: [Game] {
           return linkingObjects(Game.self, forProperty: "gameSystem")
      }
 }

 class Game : Object {
      dynamic var title = ""
      dynamic var genre = ""
      let gameSystem: GameSystem? = nil
 }

答案 1 :(得分:0)

在REALM SWIFT中删除父级和子级非常容易...您只需要编写一小段代码即可。

在这里,我试图删除名为“ Swift”的主类别,并且每当删除主类别时,所有子类别也会被删除...

do{
      try realm.write({
          realm.delete(Category.items)
          realm.delete(Category)
      })
}catch{
       print("ERROR WHILE DELETING CELL ::: \(error)")
}

简而言之,要删除子类别,您需要在后面放置“项目”。然后是父母的名字。