多对多 android room ref 额外变量

Many to many android room ref extra variable

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

一切都很好,但我想做以下补充:

我的问题是当基于查询构建 recipeWithIngredients 时,我如何让 RecipeWithIngredients 从 RecipeIngredientRef 实体获取这个 unit:String 变量?

    @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>
)

据我所知,没有 built-in 使用 Room 中当前 many-to-many 关系的方法。所以我只是想节省您的研究时间。

RecipeIngredientRef table 仅在内部用于其他两个 table 的加入,现在添加其他字段将无助于使用 @[=26 获取这些字段=] 机制.

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

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