【发布时间】:2019-12-25 03:10:44
【问题描述】:
我有两个模型类,Product 和 StoreTransaction,如下所示
产品.kt
open class Product(
var barcode: String? = null,
var name: String? = null,
var price: Double? = null,
var quantity: Double? = null
) : RealmObject()
StoreTransaction.kt
open class StoreTransaction(
var date: Date? = null,
var productList: RealmList<Product>? = null
// and other variables below
) : RealmObject()
这里我们有 3 个产品,产品 A、B 和 C,每个产品的数量相同,各 5 件
然后我购买产品 A 和 C 各 2 件并像这样保存交易
fun saveTransaction(toBuyList: ArrayList<Product>, realm: Realm) {
val date = Date()
val productList = RealmList<Product>()
productList.addAll(toBuyList.toList())
// other variables
val st = StoreTransaction(date, productList // other vars)
realm.executeTransaction {
realm.copyToRealm(st)
// update stock quantity
toBuyList.forEach { itemToBuy ->
val product = realm.where(Product::class.java)
.equalTo("barcode", itemToBuy.barcode).findFirst()
product?.quantity = product?.quantity?.minus(itemToBuy.quantity!!)
}
}
}
当我查询我的产品时,我得到了以下结果
- 产品A:3.0
- 产品 A:2.0
- 产品 B:5.0
- 产品C:3.0
- 产品C:2.0
似乎在 StoreTransaction 类中保存产品 RealmList 会在 Product 类中创建新数据。有没有办法防止这种情况?我正在尝试不显示已售出的产品。
现在我知道我可以在 Product 类中创建一个额外的变量,例如指示产品是否已售出的布尔值,然后对其进行查询。但这是正确的方式吗?
旁注:我目前的解决方案是将 StoreTransaction 中的 productList 属性更改为临时字符串(通过使用 Gson)。它工作得很好,但我很好奇如果有更好的方法来处理这个问题。
【问题讨论】:
标签: java android kotlin realm realm-list