首页 > 解决方案 > 多对多 android room ref 额外变量

问题描述

我在 Room 数据库上设置了多对多关系,如下图所示:

关系图

一切都很好,但我想做以下补充: 更新关系图

我的问题是,当在查询中构造 recipeWithIngredients 时,如何让 RecipeWithIngredients 从 RecipeIngredientRef 实体获取此单元:字符串变量?

    @Entity(indices = [Index(value = ["name"],unique = true)])
data class Recipe(
    var name: String,
    val image: String?
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "recipeID")
    var ID: Long = 0
}

@Entity(indices = [Index(value = ["name"],unique = true)])
data class Ingredient(
    val name: String,
    val image: String?,
    val amount: Int
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "ingredientID")
    var ID: Long = 0
}

@Entity(primaryKeys = ["recipeID", "ingredientID"])
data class RecipeIngredientRef(
    val recipeID: Long,
    val ingredientID: Long,
    val unit: String
)

data class RecipeWithIngredients(
    @Embedded
    val recipe: Recipe,
    @Relation(
        parentColumn = "recipeID",
        entity = Ingredient::class,
        entityColumn = "ingredientID",
        associateBy = Junction(
            value = RecipeIngredientRef::class,
            parentColumn = "recipeID",
            entityColumn = "ingredientID"
        )
    )
    val ingredients: List<Ingredient>
)

标签: androidandroid-roomandroid-room-relation

解决方案


据我所知,目前还没有使用 Room 中的多对多关系的内置方法。所以我只是想节省你研究的时间。

RecipeIngredientRef表在内部仅用于其他两个表的连接,现在添加其他字段将无助于使用 @Relations/Junction 机制获取这些字段。

您可以尝试解决方法,但它们并不那么优雅,他们需要更深入地研究 Room 的结果处理:

  1. 根本不要使用@Relation/Junction 机制,RecipeWithIngridients用两个 JOIN 编写您自己的查询(因为您应该从 3 个表中获取数据)。结果,您将获得一些原始记录集,然后您应该使用 Kotlin 集合的循环和方法将结果转换为所需的形式。
  2. 使用@Relation/Junction 机制,但在获得结果后 - 对结果进行额外处理 - 再对表进行一次查询RecipeIngredientRef并手动设置缺失unit值(再次使用循环和 Kotlin 集合的方法)。

推荐阅读