【问题标题】:Can not remove entity from Room无法从房间中移除实体
【发布时间】:2018-03-19 15:30:29
【问题描述】:

我有LoggedInUserEntity 和UserRecentSearch,其中最后一个有指向LoggedInUserEntity 的foreignKeys。当我想删除 LoggedInUserEntity 时,如果数据库中没有 UserRecentSearch 是可能的。

如何删除?

@Query("DELETE FROM loggedInUser")

我如何使用关系?

@Entity(tableName = "recentSearches",
    indices = arrayOf(Index(value = "userId",name = "idr")),
    foreignKeys = arrayOf(ForeignKey(
            entity = LoggedInUserEntity::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("userId"))
    ))

如何使用现有的UserRecentSearch 删除LoggedInUserEntity?

【问题讨论】:

    标签: android database relationship android-room android-components


    【解决方案1】:

    您需要将级联属性添加到 onDelete 方法的外键约束中,如下所示:

    @Entity(tableName = "recentSearches",
        indices = arrayOf(Index(value = "userId", name = "idr")),
        foreignKeys = arrayOf(ForeignKey(
        entity = LoggedInUserEntity::class
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("userId"),
            onDelete = CASCADE
        ))
    ))
    

    这意味着当您从数据库中删除 LoggedInUser 时,该用户使用外键的任何最近搜索也将被删除。

    【讨论】:

    • 我已保留默认 NO_ACTION,因为不得删除最近的搜索。据我了解,我的情况可能只能用 UPDATE 实体解决,但不能用 DELETE
    • 如果您删除了一个 loggedInUser 并且最近使用引用它的外键进行了搜索,您的数据库将变得不一致,这就是为什么由于这种不一致而不允许您删除 loggedInUser。如果您想保留最近的搜索,我会创建另一个表,如下所示:User、LoggedInUser 和 RecentSearches。然后,您最近的搜索引用了 User 表,并且登录的用户也引用了 user 表。这样,当您删除 LoggedInUser 时,约束仍然有效。
    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多