简体   繁体   English

你如何在 kotlin 中插入/删除所有表从一对多关系到房间?

[英]How do you insert / delete all tables from one to many relationship in kotlin with room?

I have the following entity:我有以下实体:

@Entity(tableName = "match_frames_table")
data class DbFrame(
    @PrimaryKey(autoGenerate = false)
    val frameId: Int
)

And below a data class with reference to 3 other entities, including a nested one, DbBreakWithPots :在数据 class 下方,参考其他 3 个实体,包括一个嵌套实体DbBreakWithPots

data class DbFrameWithScoreAndBreakWithPotsAndBallStack(
    @Embedded val frame: DbFrame,
    @Relation(
        parentColumn = "frameId",
        entityColumn = "frameId",
    )
    val frameScore: List<DbScore>,
    @Relation(
        parentColumn = "frameId",
        entityColumn = "frameId",
        entity = DbBreak::class
    )
    val frameStack: List<DbBreakWithPots>,
    @Relation(
        parentColumn = "frameId",
        entityColumn = "frameId"
    )
    val ballStack: List<DbBall>
)

Where DbBreakWithPots is as follows:其中DbBreakWithPots如下:

data class DbBreakWithPots(
    @Embedded val matchBreak: DbBreak,
    @Relation(
        parentColumn = "breakId",
        entityColumn = "breakId"
    )
    val matchPots: List<DbPot>
)

In my DAO, I implemented the query method, which works fine:在我的 DAO 中,我实现了查询方法,效果很好:

@Query("SELECT * FROM match_frames_table")
fun getMatchFrames(): LiveData<List<DbFrameWithScoreAndBreakWithPotsAndBallStack>>

However, at the moment I am inserting and deleting from the database manually table by table, but the fact that I have nested relations makes it tricky.但是,目前我正在逐个表手动地从数据库中插入和删除,但是我有嵌套关系的事实使它变得棘手。 Is there a way to simply insert a DbFrame and delete it through one sql request?有没有办法通过一个 sql 请求简单地插入一个DbFrame并删除它?

Let the CASCADE option of the onUpdate and onDelete actions do the work.onUpdateonDelete操作的CASCADE选项完成工作。

More specially define Foreign Keys in the child entities eg :-更特别地在子实体中定义外键,例如:-

@Entity(
    foreignKeys = [
        ForeignKey(entity = DBIdTotal::class, // Parent Entity
            parentColumns = ["id_DBIdTotal"], // column(s) in the parent
            childColumns = ["ref_DBIdTotal"], // column(s) in this table (the child)
            onDelete = ForeignKey.CASCADE, //<<<<<<<<<< if parent is deleted, the deletion is cascaded to the respective children and they are updated
            onUpdate = ForeignKey.CASCADE //<<<<<<<<<< if parent's referenced column(s) is updated then the updated value is changed in the respective children
        )
    ]
)
data class DBIdOpPedido(
    @PrimaryKey
    val id_DBIdOpPedido: Long,
    val ref_DBIdTotal: Long,
    val op: String
)

You don't have to have both actions coded, you may wish to only use onDelete .您不必对两个动作都进行编码,您可能希望只使用onDelete You may wish to look at:-你不妨看看:-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM