简体   繁体   中英

Android Room database LiveData Response with data from two different tables

I have two tables,

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

I need a liveData object that contains an object like this:

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

I understand I need some kind of join statement, but I am not sure how it should go, and what the return value should be.

it obviously cannot be

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

because ParentEntity does not contain a list of Children

You can use join statements, but common way for your case is Room's one-to-many Relations

You should add another class (without @Entity ):

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

and your dao method would be without join:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM