[英]Multiple filters in Room database android
我想使用房間數據庫查詢多個過濾器。 例如
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and orderType=:orderType and user_id=:user_id")
fun getSettlementDataTotalAmountOrderTypeUserId(fromDate: Long, toDate: Long,orderType:Int?,user_id: String?): ModelSum
我遇到了user_id
和orderType
為空的情況。 有時任何一個都是空的。 但是當我傳遞空值時,它不返回任何數據如何使用單個查詢實現過濾器?
如果您需要有效的 null,那么您需要進行一些修改。
@Entity(tableName = "settlement_table")
data class Settlement(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Long = 0,
@ColumnInfo(name = "user_id") val user_id: String? = "-1",
@ColumnInfo(name = "orderType") val longitude: Int? = -1,
@ColumnInfo(name = "total_amount") val total_amount: Int,
@ColumnInfo(name = "date_and_time") val date_and_time: Long
)
將值插入為 null 時已在其中設置默認值的表。 所以,現在你的查詢將是
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and orderType=:orderType and user_id=:user_id")
fun getSettlementDataTotalAmountOrderTypeUserId(
fromDate: Long,
toDate: Long,
orderType: Int? = -1,
user_id: String? = "-1"
): ModelSum
在這里你可以看到我們在插入時設置了默認值 -1 並且在執行查詢時我們也使用相同的值,如果orderType
和user_id
發現為空
編輯
然后你需要做一件簡單的事情,你需要創建三個同名不同參數的方法,比如方法重載。 方法 1:兩者都不為空
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and orderType=:orderType and user_id=:user_id")
fun getSettlementDataTotalAmountOrderTypeUserId(
fromDate: Long,
toDate: Long,
orderType: Int,
user_id: String
): ModelSum
方法 2: orderType 為 null
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and user_id=:user_id")
fun getSettlementDataTotalAmountOrderTypeUserId(
fromDate: Long,
toDate: Long,
user_id: String
): ModelSum
方法二:user_id為空
@Query("SELECT SUM(total_amount) as total FROM settlement_table where date_and_time>=:fromDate and date_and_time<=:toDate and orderType=:orderType")
fun getSettlementDataTotalAmountOrderTypeUserId(
fromDate: Long,
toDate: Long,
orderType: Int
): ModelSum
所以在調用這個方法時你需要make條件
if(orderType!=null && user_id!=null) {
// Call method 1
}else if(user_id!=null) {
// Call method 2
}else if(orderType!=null) {
// Call method 3
}
希望它可以幫助您解決您的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.