物體店
data class Store(
val storeId: Int,
val name: String,
val storeRank:Int
)
產品物體
data class Product(
val productId: Int,
val name: String
)
參考物體
data class Reff(
val storeId: Int,
val productId: Int,
val productRankInStore:Int
)
關系
data class StoreAndProduct(
@Embedded
val store: Store,
@Relation(
entity = Product::class,
parentColumn = "storeId",
entityColumn = "productId",
associateBy = Junction(
parentColumn = "storeId",
entityColumn = "productId",
value = Reff::class
)
)
val product: List<Product>
)
在這里,我需要使用 key productRankInStore對Products進行排序。我已經實作了這種關系并且作業正常。但我找不到任何其他方法來使用 productRankInStore 對產品進行排序
注意:相同的產品在不同的商店有不同的排名(productRankInStore)
uj5u.com熱心網友回復:
如果您有一個抽象類而不是 @Dao 注釋類的介面,那么您可以使用執行兩個階段的函式有效地覆寫 Room 處理 @Relation 的方式,并相應地對后者進行排序。
您可以通過 2 個 @Query 來做到這一點:-
- 主要(商店)和
- 二次查詢(按排名排序的產品)
然后將它們組合成一個函式,例如:-
@Dao
abstract class AllDAO {
@Query("SELECT * FROM store")
abstract fun getAllStores(): List<Store>
@Query("SELECT product.* FROM reff JOIN product ON product.productId = reff.productId WHERE reff.storeId=:storeId ORDER BY productRankInStore DESC")
abstract fun getStoreProductsSortedByRank(storeId: Int): List<Product>
@Query("")
@Transaction
fun getStoreAndProductsSortedByProductRank(): List<StoreAndProduct> {
val rv = arrayListOf<StoreAndProduct>()
for (store in getAllStores() /* obviously change initial query if desired */) {
rv.add(StoreAndProduct(store,getStoreProductsSortedByRank(store.storeId)))
}
return rv
}
}
然后你可以使用: -
dao.getStoreAndProductsSortedByProductRank()
例如,如果您有以下資料:-
和
并且排名 1 是頂部,然后是以下
for(s in dao.getStoreAndProductsSortedByProductRank()) {
Log.d("DBINFO","Store is ${s.store.name}")
for (p in s.product) {
Log.d("DBINFO","\tProduct is ${p.name}")
}
}
將輸出:-
2022-03-26 06:43:15.753 D/DBINFO: Store is Store1
2022-03-26 06:43:15.753 D/DBINFO: Product is ProductA
2022-03-26 06:43:15.753 D/DBINFO: Product is ProductB
2022-03-26 06:43:15.753 D/DBINFO: Product is ProductC
2022-03-26 06:43:15.753 D/DBINFO: Store is Store2
2022-03-26 06:43:15.753 D/DBINFO: Product is ProductC
2022-03-26 06:43:15.753 D/DBINFO: Product is ProductA
2022-03-26 06:43:15.753 D/DBINFO: Product is ProductB
2022-03-26 06:43:15.753 D/DBINFO: Store is Store3
2022-03-26 06:43:15.753 D/DBINFO: Product is ProductC
2022-03-26 06:43:15.753 D/DBINFO: Product is ProductB
2022-03-26 06:43:15.754 D/DBINFO: Product is ProductA
注意rankInStore 將不可用(根據您的 StoreAndProduct)。
- 如果您需要可用的 rankInStore,那么您需要執行一些操作,例如擁有并使用 ProductAndRank POJO。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451666.html
下一篇:運行氣流網路服務器時出現氣流錯誤