简体   繁体   English

房间查询一对多关系

[英]Room querying one to many relationship

How can we query all entities with their one to many relationship with Room? 我们如何查询所有具有Room一对一关系的实体?

Say we have a User Entity : 假设我们有一个用户实体

@Entity
class User(@PrimaryKey(autoGenerate = true) var id: Long?, var name: String)

and a Pet Entity : 和一个宠物实体

@Entity(foreignKeys = [(ForeignKey(entity = User::class,
    parentColumns = ["id"],
    childColumns = ["userId"],
    onDelete = ForeignKey.CASCADE))])
public class Pet(@PrimaryKey(autoGenerate = true),
    var name: String,
    var userId: Long?,
    @Ignore var user: User?)

Normally we would query all pets like this: 通常我们会像这样查询所有宠物:

@Dao
interface PetsDao {
    @Query("SELECT * FROM pets")
    fun getAll(): Flowable<List<Pet>>
}

But how can we make it so that the User is attached to the Pet object automatically? 但是,如何使用户自动附加到Pet对象上呢? Like the query would be: 就像查询将是:

@Dao
interface PetsDao {
    @Query("SELECT * FROM pets p JOIN users u ON u.id = p.userId")
    fun getAllWithUser(): Flowable<List<Pet>>
}

And then we could use pet.user.name without having to query the user separately. 然后我们可以使用pet.user.name,而不必分别查询用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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