我遇到错误
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?
答案 0 :(得分:1)
对于我来说,错误消息是有道理的:
要摆脱错误,您可以:
indices = [Index("id", unique = true)]
@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
)