这对我来说非常棘手,因为我不知道是否可以通过SQLite查询或递归调用某个函数来完成.它变得复杂了,因为我也用Flow
和LiveData
搭配ViewModel
基本上,我的实体是这样的
@Entity(
foreignKeys = [
ForeignKey(
entity = Item::class,
parentColumns = [ "id" ],
childColumns = [ "parentId" ],
onDelete = ForeignKey.CASCADE
),
],
indices = [
Index(value = [ "parentId" ]),
Index(value = [ "sectionId" ])
],
)
class Item(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
var parentId: Long? = null,
val name: String
)
现在,假设我有5个项目,每个项目都是下一个项目的父母
Item (id = 1, parentId = null, name = "Root item")
Item (id = 2, parentId = 1, name = "Item 2")
Item (id = 3, parentId = 2, name = "Item 3")
Item (id = 4, parentId = 3, name = "Item 4")
Item (id = 5, parentId = 4, name = "Item 5")
所以,我想要的是得到Item 5和它的所有祖先,这是Item 4,因为它是它的父母,Item 3,因为它是Item 4的父母,依此类推到第一个(它没有父母,所以它是我们停下来的地方)
现在我的刀有点乱,我有点卡住了.你认为这是如何实现的?
@Dao
interface ItemDao {
@Query("SELECT * FROM Item WHERE itemId = :itemId")
fun getById(itemId: Long): Flow<Item>
fun getAncestors(itemId: Long): Flow<List<Item>> = flow {
val item = getById(itemId)
item.collect { it ->
if (it.parentId != null) {
val parent = getAncestors(it.parentId!!)
val items = combine(item, parent ) { i, p ->
val allItems: ArrayList<Item> = arrayListOf()
allItems.add(i)
allItems.add(p)
allItems
}
emitAll(items)
} else {
emitAll(item)
}
}
}
}
这不起作用(我不完全明白),很可能是因为错误地使用了流.我需要一个替代方案或一点帮助来理解这一点并摆脱困境