android - 如何使用“房间关系”注释一次加入多个对象?

标签 android sql kotlin android-room

最近在Room中了解到诸如Relation注解之类的东西,但由于误解而立即陷入僵局。我有以下数据库模型:
数据库类别

@Entity(tableName = "categories")
data class DatabaseCategory(
    @PrimaryKey
    val id: Int = 0,
    val name: String ="",
    val description: String = "",
    @ColumnInfo(name = "picture_url") val pictureUrl: String = "",
)
数据库产品
@Entity(tableName = "products",
    foreignKeys = [
        ForeignKey(entity = DatabaseCategory::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("category_id"),
            onDelete = ForeignKey.CASCADE
        )],
    indices = [
        Index(value = ["category_id"])]
)
data class DatabaseProduct(
    @PrimaryKey
    val id: Long = 0L,
    val name: String,
    val price: Float,
    val discount: Float = 0f,
    val description: String = "",
    @ColumnInfo(name = "category_id") val categoryId: Int,
    @ColumnInfo(name = "picture_url") val pictureUrl: String,
    val recent: OffsetDateTime? = null
)
DatabaseCartItem
@Entity(tableName = "cart",
    foreignKeys = [
        ForeignKey(entity = DatabaseProduct::class,
            parentColumns = arrayOf("id"),
            childColumns = arrayOf("product_id"),
            onDelete = ForeignKey.CASCADE
        )],
    indices = [
        Index(value = ["product_id"])])
data class DatabaseCartItem(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    @ColumnInfo(name = "product_id")
    val productId: Long,
    var quantity: Int = 0
)
我想出了在最简单的情况下如何使用此工具的方法。
data class DatabaseCategoryWithProducts(
    @Embedded val category: DatabaseCategory,
    @Relation(
        parentColumn = "id",
        entityColumn = "category_id"
    )
    val products: List<DatabaseProduct>
)
问题是:如何为Room和DAO查询指定一个对象,以便我可以得到这样的对象
data class DomainCartItem(
    val id: Long,
    val product: Product,
    val category: Category,
    val quantity: Int
)

最佳答案

对于您想要的内容,请尝试下一个对象:

data class DomainCartItem(
    @Embedded val product: DatabaseProduct, // <-- here you get your id and quantity
    
    @Relation(
        parentColumn = "category_id",
        entityColumn = "id"
    )
    val category:DatabaseCategory,
    @Relation(
        parentColumn = "id",
        entityColumn = "productId"
    )
    val cartItem:DatabaseCartItem,
)
和道方法:
@Transaction
@Query("SELECT * FROM products")
fun getDomainCartItems(): List<DomainCartItem>
更新
要仅获取包含在CartItems中的产品,可以使用另一个查询:
@Transaction
@Query("SELECT * FROM products JOIN cart on products.id = cart.productId")
fun getDomainCartItems(): List<DomainCartItem>

关于android - 如何使用“房间关系”注释一次加入多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64519483/

相关文章:

android - 如何在 Kotlin 中调用 ArrayAdapter.addAll 方法?

Android - 数据库类结构 OOP

Android 设备 (GPS) 方向

mysql - 选择月份和年份内的所有记录

mysql - 使用 MySQL 选择随时间变化的大量数据的一部分

gradle - 使用Kotlin和Gradle创建胖子-编译还是实现?

android - 图书馆能否避免暴露其对 Timber 的使用?

android - 自定义全屏行为

mysql - 我的架构中是否做错了什么?

java - Kotlin 函数类型在运行时的 Java 类型是什么?