会议室中的复合关键关系

时间:2020-05-25 16:49:50

标签: android kotlin android-room android-jetpack

我遇到错误

error: BookGroupEntry has a foreign key (bookGroupParameterId) that references BookGroupParameter (id) but BookGroupParameter does not have a unique index on those columns nor the columns are its primary key. SQLite requires having a unique constraint on referenced parent columns so you must add a unique index to BookGroupParameter that has (id) column(s).

它完全让我感到困惑,因为我没有错误所报告的情况

我的BookGroupParameter表如下

@Entity(
    tableName = "BookGroupParameters",
    primaryKeys = ["id", "parameterId", "bookGroupId"],
    indices = [Index("id")],
    foreignKeys = [
        ForeignKey(
            entity = Parameter::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("parameterId"),
            onDelete = ForeignKey.CASCADE
        ),

        ForeignKey(
            entity = BookGroup::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("bookGroupId"),
            onDelete = ForeignKey.CASCADE
        )]
)
data class BookGroupParameter(
    @NonNull
    var id: Int,
    val bookGroupId: Int,
    val parameterId: Int
) {
}

这是我的BookGroupEntry表

@Entity(
    tableName = "BookGroupEntries",foreignKeys = [
        ForeignKey(
            entity = BookGroupParameter::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("bookGroupParameterId"),
            onDelete = ForeignKey.CASCADE
        )]
)
data class BookGroupEntry(
    @PrimaryKey
    var id: Int,
    var value: String,
    val bookGroupParameterId:Int
)

为什么告诉我BookGroupEntry中的FK在BookGroupParameters表中未定义为PK?

1 个答案:

答案 0 :(得分:1)

对于我来说,错误消息是有道理的:

  • Index(“ id”)确实不是唯一索引
  • “ id”列不是BookGroupParameter表中的主键(因为它的主键是您编写的复合键)

要摆脱错误,您可以:

  1. 要使表 BookGroupParameter 中的索引唯一:
    indices = [Index("id", unique = true)]
  1. BookGroupParameter 的组合主键放在 BookGroupEntry 中:
@Entity(
    tableName = "BookGroupEntries",foreignKeys = [
        ForeignKey(
            entity = BookGroupParameter::class,
            parentColumns = arrayOf("id","bookGroupId","parameterId"),
            childColumns = arrayOf("bookGroupParameterId","bookGroupParameterBookGroupId","bookGroupParameterParameterId"), // changed
            onDelete = ForeignKey.CASCADE
        )]
)
data class BookGroupEntry(
    @PrimaryKey
    var id: Int,
    var value: String,
    val bookGroupParameterId:Int,
    val bookGroupParameterBookGroupId:Int, // added
    val bookGroupParameterParameterId:Int // added
)