@Entity class Parent { @PrimaryKey var id: Int = 0 var name: String = "" }
@Entity(foreignKeys = [ForeignKey(entity = Parent::class, parentColumns = ["id"], childColumns = ["parentId"])]) class Child { @PrimaryKey var id: Int = 0 var parentId: Int = 0 var name: String = "" }
@Dao interface ParentDao { // 查询一个 Parent 包含的所有 Child,并限制 Child 的 name 属性为指定值 @Transaction @Query("SELECT * FROM Parent WHERE id = :parentId") fun getParentWithChildren(parentId: Int): ParentWithChildren }
// 定义一个数据类 ParentWithChildren,用于存储查询结果
data class ParentWithChildren(
@Embedded val parent: Parent,
@Relation(parentColumn = "id", entityColumn = "parentId") val children: List
val parentWithChildren = parentDao.getParentWithChildren(parentId) val matchedChildren = parentWithChildren.children.filter { it.name == "指定值" }