【问题标题】:Composite key relations in RoomRoom 中的复合键关系
【发布时间】:2020-05-25 16:49:50
【问题描述】:

我收到一个错误

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?

【问题讨论】:

    标签: android kotlin android-room android-jetpack


    【解决方案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
    )
    

    【讨论】:

    • 完全正确。但是错误不应该说“id”不是主键。它可能使用了其他一些措辞,例如您需要指定复合材料中的哪个 PK 是唯一的。谢谢兄弟
    猜你喜欢
    • 2018-10-25
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 2017-03-14
    相关资源
    最近更新 更多