[英]Update mutiple rows in table using Realm in Android
我正在使用Realm将我的值存储在本地数据库中。
我的要求是我需要根据某些条件更改一个字段status=1
。
我尝试了以下方法来完成此任务。 它工作正常。
RealmResults<NotificationOrder> notificationOrders=realm
.where(NotificationOrder.class)
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.property_id,ConstantMethod.getPreference(getActivity(),UserDefault.kPropertyId))
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.status,0)
.findAll();
for (NotificationOrder order:notificationOrders) {
realm.beginTransaction();
order.setStatus(1);
realm.commitTransaction();
}
现在我的本地数据库中可能有 1000 行这样的行,并且使用 for 循环更新单行似乎不是正确的方法。
所以我的问题是:有没有像 Realm 中的MYSQL
更新查询那样的方法,我们可以通过单个语句更新状态 = 0 的所有行,而不是一一更新单行?
谢谢。
如果我知道正确,事务中的对象应该被管理,所以
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<NotificationOrder> notificationOrders = realm
.where(NotificationOrder.class)
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.property_id,ConstantMethod.getPreference(getActivity(),UserDefault.kPropertyId))
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.status,0)
.findAll();
for(NotificationOrder order : notificationOrders) {
order.setStatus(1);
}
}
});
应该够了。
您可以通过setValue
方法进行批量更新,如下所示:
realm.where(NotificationOrder.class)
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.property_id,ConstantMethod.getPreference(getActivity(),UserDefault.kPropertyId))
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.status,0)
.findAll()
.setValue(RealmConstants.REALM_FIELD_NAME,value); // 1st parameter is field name, 2nd is value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.