假设我有每个可以有许多类别的项目:
@Entity(tableName = "items")
data class Item(
@PrimaryKey val item_id: Long,
val external_id: String,
val name: String,
val price: Long,
val image: String?,
var indexInResponse: Int = -1
)
@Entity(tableName = "categories")
data class Category(
@PrimaryKey val cat_id: Long,
val name: String,
val image: String?,
var indexInResponse: Int = -1
)
//-------
@Entity(tableName = "items_with_categories", primaryKeys = ["item", "cat"], indices = [Index(value = ["cat"])])
data class ItemCategoryCrossRef(
val item: Long,
val cat: Long
)
data class ItemWithCategories(
@Embedded val item: Item,
@Relation(
parentColumn = "item_id",
entityColumn = "cat_id",
associateBy = Junction(
ItemCategoryCrossRef::class,
parentColumn = "item",
entityColumn = "cat")
)
val cats: List<Category>
)
我可以使用它检索所有具有类别的项目,效果很好:
@Transaction
@Query("SELECT * FROM items ORDER BY indexInResponse ASC")
abstract fun getItemsWithCategories(): DataSource.Factory<Int, ItemWithCategories>
如何使用 Room 或 SQL 根据 ID 检索具有特定类别的项目?
@Transaction
@Query("SELECT * FROM items WHERE ??<something>?? LIKE :catID ORDER BY indexInResponse ASC")
abstract fun getItemsWithCategoriesByCatID(catID: Long): DataSource.Factory<Int, ItemWithCategories>
我不认为这是可能的,显然Categories 列表是POJO 列表,它是一个嵌套关系。那么在 SQL 中使用原始查询执行此操作的唯一方法是什么?
这是我发现的最接近的问题,但此处答案中的 DatabaseView 对其 WHERE 子句使用硬编码字段,我需要能够在运行时指定类别 ID。