【问题标题】:Android Room query objects with at least one item existing from another listAndroid Room 查询对象,其中至少一个项目存在于另一个列表中
【发布时间】:2020-10-21 13:36:19
【问题描述】:

让我先展示一些代码。我在数据库中有症状对象列表:

val symptomA = Symptom(id = 0, name = "SymptomA")
val symptomB = Symptom(id = 1, name = "SymptomB")
val symptomC = Symptom(id = 2, name = "SymptomC")
val symptomD = Symptom(id = 3, name = "SymptomD")

我还有数据库中的疾病对象列表:

val diseaseA = Disease(id = 0, name = "DiseaseA", listOfSymptoms = listOf(0, 1))
val diseaseB = Disease(id = 1, name = "DiseaseB", listOfSymptoms = listOf(1, 2, 3))
val diseaseC = Disease(id = 2, name = "DiseaseC", listOfSymptoms = listOf(0, 2))
val diseaseD = Disease(id = 3, name = "DiseaseD", listOfSymptoms = listOf(3))

我正在使用的一些类:

疾病

@Entity(tableName = "diseases")
data class Disease(
    @PrimaryKey @NotNull val id: Int,
    @NotNull val name: String,
    @ColumnInfo(name = "symptoms_ids") val symptomsIds: String,
    ...)

症状道

@Dao
interface DiseaseDao {

    @Query("SELECT * FROM diseases WHERE id LIKE :id LIMIT 1")
    fun getDisease(id: Int): Disease

    @Query("SELECT * FROM diseases")
    fun getAllDiseases(): LiveData<List<Disease>>

    @Query("SELECT * FROM diseases WHERE symptoms_ids IN (:symptoms)")
    fun getDiseasesWithSymptoms(symptoms: List<Int>): LiveData<List<Disease>>
    // The query from question ^
}

转换器(在db类中用于将String转换为列表)

class Converter {

    @TypeConverter
    fun fromString(stringListString: String) = stringListString.split(";").map { it.toInt() }

    @TypeConverter
    fun toString(stringList: List<Int>) = stringList.joinToString(";")
}

问题

是否可以按房间查询列表中至少有一个症状 id 的所有疾病?我正在使用 MVVM 模式,是否可以在 DAO 中完成,或者我应该在 Repository 或 ViewModel 类中创建一个函数?

第一个例子:

输入 = listOf(0)

结果 = listOf(diseaseA, diseaseC)

第二个例子:

输入 = listOf(1, 2)

结果 = listOf(diseaseA, diseaseB, diseaseC)

【问题讨论】:

    标签: android kotlin mvvm android-room


    【解决方案1】:

    您必须在 ViewModel 中执行此操作,因为 SQL/Room 不理解 List 类型并且无法为您执行此类检查。

    fun getDiseasesWithSymptoms(symptoms: List<Int>): LiveData<List<Disease>> {
        return Transformations.map(diseaseDao.getAllDiseases()) { diseases ->
            diseases.filter { disease ->
                disease.listOfSymptoms.any { symptoms.contains(it)}
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多