简体   繁体   English

在 Android 中使用 Realm 更新表中的多行

[英]Update mutiple rows in table using Realm in Android

I am using Realm to store my values in local database.我正在使用Realm将我的值存储在本地数据库中。

My requirement is that i need to change one field status=1 based on some condition.我的要求是我需要根据某些条件更改一个字段status=1

I have tried following method to accomplish this task.我尝试了以下方法来完成此任务。 And it is working fine.它工作正常。

   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();
    }

Now there may be 1000 of such rows in my local db and using for loop to update single row doesn't seem proper way.现在我的本地数据库中可能有 1000 行这样的行,并且使用 for 循环更新单行似乎不是正确的方法。

So my question : Is there any way like MYSQL Update Queries in Realm by which we can update all rows having status=0 by single statement instead of updating single row one by one ?所以我的问题有没有像 Realm 中的MYSQL更新查询那样的方法,我们可以通过单个语句更新状态 = 0 的所有行,而不是一一更新单行?

Thanks.谢谢。

If I know right, the objects in the transaction ought to be managed, so如果我知道正确,事务中的对象应该被管理,所以

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);
        }
    }
});

Should be sufficient.应该够了。

You can do, bulk update by setValue method like this:您可以通过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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM