Android 房间数据库 LiveData 响应来自两个不同表的数据

Android Room database LiveData Response with data from two different tables

我有两个表,

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

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

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

我知道我需要某种连接语句,但我不确定它应该如何进行,以及 return 值应该是多少。

显然不能

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

因为 ParentEntity 不包含 Children 列表

您可以使用连接语句,但您的情况的常用方法是 Room 的 one-to-many Relations

您应该添加另一个 class(没有 @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>>