'How to access each column on many-to-many relationships in room database android

so here is the diagram of the database enter image description here

What i wanna do is to join all these tables to get every column in each table, i have seen many-to-many relationship diagram examples in room example example1 example2 example3 but on these examples the relation table (OrderItem) only has 2 columns which the ids of the other tables (Order, Item), they ignore the value on relation table. But for me i also want to access/get the columns on relation table (OrderItem) that is quantity and total_price

I have tried something like this

ItemModel

@Entity(tableName = "item_table")
data class ItemModel(

  @PrimaryKey
  @ColumnInfo(name = "id")
  val itemId: String,
  @ColumnInfo(name = "item_name")
  var itemName: String,
  @ColumnInfo(name = "item_price")
  var itemPrice: String,
  @ColumnInfo(name = "item_stock")
  var itemStock: Int
)

OrderModel

@Entity(tableName = "order_table")
data class OrderModel(

  @PrimaryKey
  @ColumnInfo(name = "id")
  val orderId: String,
  @ColumnInfo(name = "order_total_price")
  val orderTotalPrice: String,
  @ColumnInfo(name = "order_pay")
  val orderPay: String,
  @ColumnInfo(name = "order_exchange")
  val orderExchange: String
)

OrderItemModel

@Entity(tableName = "order_item_table", primaryKeys = ["order_id", "item_id"])
data class OrderItemModel(

  @ColumnInfo(name = "order_id", index = true)
  var orderId: String,
  @ColumnInfo(name = "item_id", index = true)
  var itemId: String,
  @ColumnInfo(name = "quantity")
  val qty: Int,
  @ColumnInfo(name = "price")
  val price: String,
  @ColumnInfo(name = "total_price")
  val totalPrice: String
)

OrderWithItems

data class OrderWithItems(

  @Embedded
  val order: OrderModel,

  @Relation(
      entity = OrderItemModel::class,
      parentColumn = "id",
      entityColumn = "order_id"
  )
  val orderItems: List<OrderItemModel>,

  @Relation(
      entity = ItemModel::class,
      parentColumn = "id",
      entityColumn = "id",
      associateBy = Junction(
          OrderItemModel::class,
          parentColumn = "order_id",
          entityColumn = "item_id"
      )
  )
  val items: List<ItemModel>
)

But this give me inconcistence result, sometime the item_name on index 0 (from ItemModel) matches with the quantity on index 0 (from OrderItemModel) and sometimes not. Then what is the correct way to access each column on every table using room database?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source