Android Room外键

时间:2018-07-03 09:56:39

标签: android kotlin android-room android-architecture-components

  

错误:产品具有引用类别的外键(categoryId)   (id),但Category在这些列上没有唯一索引,   列是其主键。 SQLite需要具有唯一性   对引用的父列的约束,因此您必须添加唯一索引   到具有(id)列的类别。

类别

@Entity(
  tableName = "categories",
  indices = [Index("id"), Index("languageId")],
  primaryKeys = ["id", "languageId"],
  foreignKeys = [(ForeignKey(
    entity = Language::class,
    parentColumns = ["id"],
    childColumns = ["languageId"]
  ))]
)
@TypeConverters(ChildCategoryTypeConverter::class)
data class Category(
  val id: String,
  val name: String,
  val image: String?,
  val children: List<Category>?
) {

  @field:Transient var selected = false
  lateinit var languageId: String
}

产品

@Entity(
  tableName = "products",
  indices = [Index("id"), Index("languageId"), Index("categoryId")],
  primaryKeys = ["id", "languageId", "categoryId"],
  foreignKeys = [
    (ForeignKey(
      entity = Language::class,
      parentColumns = ["id"],
      childColumns = ["languageId"]
    )),
    (ForeignKey(
      entity = Category::class,
      parentColumns = ["id"],
      childColumns = ["categoryId"]
    ))
  ]
)
data class Product(
  val id: String,
  val title: String?,
  val description: String?,
  @field:SerializedName("calory") val calorie: String?,
  val delivery: String?,
  val price: String?,
  @field:SerializedName("main_image") val mainImage: String?,
  @field:SerializedName("detail_image") val detailImage: String?
) {

  lateinit var languageId: String
  lateinit var categoryId: String
}

我知道在Category类中制作indices = [Index("id", unique = true), Index("languageId")]可以解决问题,但是我不明白这里有什么问题。引用的外键已在Category类中定义为主键。

您能在这里指导我吗?预先感谢。

0 个答案:

没有答案