You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Room:如何从关联表提取订单关联商品及数量数据?

获取指定订单详情的SQL查询与Room关系类定义

一、SQL查询语句

要获取指定订单的详情(包含对应商品及数量),通过关联三张表即可实现,示例SQL如下(将?替换为目标订单ID):

SELECT o.*, p.*, op.quantity
FROM Orders o
JOIN OrderProductCrossRef op ON o.orderId = op.orderId
JOIN Products p ON op.productId = p.productId
WHERE o.orderId = ?;

该语句通过订单ID关联交叉表与商品表,一次性获取订单基础信息、对应商品详情及购买数量。

二、Room关系类定义

要匹配你需要的{ order: OrderEntity, productlist: {ProductEntity ,quantity} }结构,需定义以下数据类:

1. 带数量的商品包装类

先封装商品实体与对应数量:

data class ProductWithQuantity(
    @Embedded val product: ProductEntity,
    @ColumnInfo(name = "quantity") val quantity: Int
)

2. 订单详情关系类

定义包含订单实体及对应商品列表的关系类,通过@Relation自动处理关联逻辑:

data class OrderWithProducts(
    @Embedded val order: OrderEntity,
    @Relation(
        parentColumn = "orderId",
        entityColumn = "productId",
        associateBy = Junction(
            value = OrderProductCrossRef::class,
            parentColumn = "orderId",
            entityColumn = "productId"
        ),
        projection = ["quantity"]
    )
    val productlist: List<ProductWithQuantity>
)

3. DAO层查询方法

在DAO接口中添加事务查询方法,直接返回上述关系类:

@Dao
interface OrderDao {
    @Transaction
    @Query("SELECT * FROM Orders WHERE orderId = :orderId")
    suspend fun getOrderWithProducts(orderId: Int): OrderWithProducts?
}

@Transaction确保查询操作的原子性,@Relation会自动完成三张表的关联查询,将结果封装为你需要的结构。

内容的提问来源于stack exchange,提问作者ihsan arslan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 10:42:14