【问题标题】:Android Room database LiveData Response with data from two different tablesAndroid Room 数据库 LiveData 响应来自两个不同表的数据
【发布时间】:2020-08-05 11:26:48
【问题描述】:

我有两张桌子,

ParentEntity ( id: String, name: String)
ChildEntity (id: String, name: String, parentId: String)

我需要一个包含如下对象的 liveData 对象:

ParentEntity(id: String, name: String, children: List<ChildEntity>)

我知道我需要某种 join 语句,但我不确定它应该如何进行,以及返回值应该是什么。

显然不可能

@Query("JOIN STATEMENT")
fun queryParentsWithChildren(): LiveData<List<ParentEntity>>

因为 ParentEntity 不包含 Children 列表

【问题讨论】:

    标签: android android-room android-livedata


    【解决方案1】:

    您可以使用 join 语句,但常见的方法是 Room 的 one-to-many Relations

    你应该添加另一个类(没有@Entity):

    data class ParentWithChildren(
        @Embedded val parent: ParentEntity,
        @Relation(
              parentColumn = "id",
              entityColumn = "parentId"
        )
        val children: List<ChildEntity>
    )
    

    你的 dao 方法将没有加入:

    @Transaction
    @Query("select * from parent") // <- replace 'parent' with your actual table's name
    fun queryParentsWithChildren(): LiveData<List<ParentWithChildren>>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 2021-04-13
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 2021-04-15
    相关资源
    最近更新 更多