This is very tricky for me because I don't know if it can be done with a SQLite query or by recursively calling some function. It gets complicated because I also use Flow
and LiveData
with ViewModel
Basically, my entity looks like this
@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
)
Now, imagine I have 5 items, each one parent of the next one
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")
So, what I want is to get Item 5 and all its ancestors, that is Item 4 because it is its parent, Item 3 because it's the parent of Item 4 and so on to the first one (which has no parent, therefore it is where we stop)
At the moment I have this mess in my DAO and I am kinda stuck. How do you think this can be achieved?
@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)
}
}
}
}
This does not work (I don't get everything) and it's most likely because of the wrong use of flows. I need an alternative or a little help to understand this and get unstuck