Android上的简单杂货应用程序。所有东西都是本地的,使用Room DataBase,使用MVVM模型和Kotlin。我有一个DataBase,一个Repository和一个ViewModel。我正在练习这个应用程序,我现在对DataBase感到不舒服。
我有两张桌子:
ShoppingItems (我想要的东西)ReferenceItems (我通常买的东西,知道价格)在ReferenceItems表中有3列:
在ShoppingItems表中,我有以下列:
现在,一切都完美地使用LiveData<>读取信息,如数量或总价。
我的问题是:我能否仅使用ReferenceItems ShoppingItems 表中的 Id来获取单元价格。
实际上,如果需要,用户将能够在ReferenceItems表中编辑单元价格。我希望应用程序只更新ReferenceItems表中的一个字段。在实际情况下,我必须更新ReferenceItems表和ShoppingItems表中的价格。
发布于 2020-05-08 20:12:11
我能否仅使用ReferenceItems表中的ShoppingItems Id来获取单价
可以,停那儿吧。
场景1(没有辅助类)。
将道中的查询更改为如下所示:
@Query("select shoppingItems.*, referenceItems.unitPrice from shoppingItems left join referenceItems on shoppingItems.referenceId=referenceItems.id")
LiveData<List<ShoppingItems>> getShoppingItems()但是要做到这一点,您必须将"unitPrice“字段保留在"shoppingItems”类中(当然,您可以在插入数据时将其保留为空)。您可以使用@ not注释,尝试不将这个字段持久化为db,但我不能保证在这种情况下查询会返回代价。
场景2(带有辅助类)。
所需步骤:
public class ShoppingItemsWithPrice { @Embedded public ShoppingItems shoppingItems; @Relation(parentColumn = "referenceId", entityColumn = "id") public ReferenceItems referenceItems; }@Query("select * from shoppingItems") LiveData<List<ShoppingItemsWithPrice>> getShoppingItemsWithPrice()因此,查询返回包含两个表中所有内容的对象。您可以根据这篇文章对其进行优化(只获得一个所需的字段)
https://stackoverflow.com/questions/61683787
复制相似问题