android - Realm (Android/Kotlin) - 如何执行一个查询,允许您测试所有对象是否作为值数组中值的一部分匹配
问题描述
语境 :
- 某些内容(工作表、类别等)受组保护。(内容类有 2 个 RealmLists 组,第一个“groupsOneOf”和第二个“groupsAllOf”)
- 用户可以在组中(用户有一个 RealmList “组”)
- 某些内容仅对至少在内容组之一中的用户可用。
- 某些内容仅适用于所有内容组中的用户。
对于“至少在一个内容组中”,我在文档中找到了 '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 时,我不必忘记调用这个函数:/
一些帮助将不胜感激。
解决方案
推荐阅读
- methods - 是否有方法注释表明它与指定的功能接口匹配?
- excel - 从 For Next 循环中剪切和粘贴的代码。我怎样才能专门使用 For Each 循环来做到这一点?
- apache-spark - 火花数据框查询总和
- javascript - 使用 javascript 中的正则表达式过滤降价中的列表标记
- json - 用powershell修改json文件
- django - Django - 保存对模型对象所做的更改并在发布时呈现
- pyspark - 将文件名输出到pyspark中的最终文件夹
- c# - 为什么这个泛型类会产生编译器错误?
- java - 在java中读取文件并将其内容放入二维数组
- git - 如何压缩选择的提交