android - 多对多 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>
)
解决方案
据我所知,目前还没有使用 Room 中的多对多关系的内置方法。所以我只是想节省你研究的时间。
该RecipeIngredientRef
表在内部仅用于其他两个表的连接,现在添加其他字段将无助于使用 @Relations/Junction 机制获取这些字段。
您可以尝试解决方法,但它们并不那么优雅,他们需要更深入地研究 Room 的结果处理:
- 根本不要使用@Relation/Junction 机制,
RecipeWithIngridients
用两个 JOIN 编写您自己的查询(因为您应该从 3 个表中获取数据)。结果,您将获得一些原始记录集,然后您应该使用 Kotlin 集合的循环和方法将结果转换为所需的形式。 - 使用@Relation/Junction 机制,但在获得结果后 - 对结果进行额外处理 - 再对表进行一次查询
RecipeIngredientRef
并手动设置缺失unit
值(再次使用循环和 Kotlin 集合的方法)。
推荐阅读
- java - Android Studio - 如何在不使用按钮的情况下将数据从活动传递到片段
- nginx - NGINX-RTMP-MODULE:[错误] hls:强制片段拆分
- python - 如何在 Pandas 中为多个同名行启动这个给定 DataFrame 的 for 循环?
- python - Convert time to categorical variable
- python-3.x - 如何在 Matplotib 中的 x 轴下方放置一个简单的标题?
- javascript - 有没有办法在 JavaScript 中修改部分响应数据时保留 api 响应数据
- mysql - 将字符串转换为十进制或浮点 mysql
- r - R中的For循环仅适用于最后一个元素
- slurm - 没有节点约束的 SLURM 调度任务
- disk - fdisk 实用程序如何在 SSD 上使用 CHS 寻址?