首页 > 解决方案 > Realm (Android/Kotlin) - 如何执行一个查询,允许您测试所有对象是否作为值数组中值的一部分匹配

问题描述

语境 :

  1. 某些内容(工作表、类别等)受组保护。(内容类有 2 个 RealmLists 组,第一个“groupsOneOf”和第二个“groupsAllOf”)
  2. 用户可以在组中(用户有一个 RealmList “组”)
  3. 某些内容仅对至少在内容组之一中的用户可用。
  4. 某些内容仅适用于所有内容组中的用户。

对于“至少在一个内容组中”,我在文档中找到了 'in' 运算符:

这允许您测试对象是否匹配值数组中的任何值。

但是对于第二个,没有办法执行这种查询。我在其他帖子中搜索了解决方案,但有些人似乎说现在不支持。在 iOS 中,它似乎在 NSPredicate 中可用,但在 java 中不可用。

这是我的代码:

fun <E: RealmObject> RealmQuery<E>.groupsAllowed(): RealmQuery<E>{
    val userGroupsIds = realm.queryUserConnected()?.findFirst()?.groups?.toGroupIds()
    if(userGroupsIds == null || userGroupsIds.isEmpty()){
        isEmpty("groupsAllOf")
        isEmpty("groupsOneOf")
    }else{
        beginGroup()
            beginGroup()
                isEmpty("groupsOneOf")
                or()
                `in`("groupsOneOf.id", userGroupsIds.toTypedArray())
            endGroup()
            //beginGroup()
                //isEmpty("groupsAllOf")
                //or()
                //TODO
            //endGroup()
        endGroup()
    }
    return this
}

目前,当我获得 groupsAllOf 的 RealmResults 时,我正在执行后过滤器:

fun <E: RealmObject> E.groupsAllowed(userGroupIds: List<String>): E?{
    val groupsAllOf: RealmList<Group>? = when(this){
        is Sheet -> groupsAllOf
        is Category -> groupsAllOf
        else -> null
    }
    if(groupsAllOf == null || groupsAllOf.isEmpty()){
        return this
    }else{
        return if(userGroupIds.containsAll(groupsAllOf.toGroupIds())) this else null
    }
}

fun <E: RealmObject> RealmResults<E>.groupsAllowed(): List<E>{
    val userGroupIds = realm.queryUserConnected().findFirst()?.groups?.toGroupIds()?: emptyList()
    val listAllowed = arrayListOf<E>()
    this.forEach { it.groupsAllowed(userGroupIds)?.let { contentAllowed ->  listAllowed.add(contentAllowed) } }
    return listAllowed
}

fun RealmList<Group>.toGroupIds(): List<String> = arrayListOf<String>().apply { this@toGroupIds.forEach { group -> this.add(group.id) } }

但这很烦人,因为当我得到 RealmResults 时,我不必忘记调用这个函数:/

一些帮助将不胜感激。

标签: androidrealmrealm-list

解决方案


推荐阅读