更新 table 中与另一个 table(2 table 案例)android 房间数据库中的字段相关的项目列

Update an item column in a table related to a field in an other table (2 tables case) android room database

Android 上的简单杂货应用。使用 Room 数据库,使用 MVVM 模型和 Kotlin,一切都是本地的。我有一个 DataBase、一个 Repository 和一个 ViewModel。我正在使用这个应用程序进行练习,目前我对 DataBase 感到不适应table。

我有两个 table:

ReferenceItems table 我有 3 列:

ShoppingItemstable我有以下列:

现在,使用 LiveData<> 读取数量或总价等信息,一切都完美无缺。

我的问题是:我可以只使用ShoppingItems table中的ReferenceItems Id来获取单价吗

事实上,如果需要,用户可以在 ReferenceItems table 中编辑单价。我希望该应用仅更新 ReferenceItems table 中的一个字段。在实际情况下,我将不得不更新 ReferenceItems table AND ShoppingItems table.

中的价格

Can I use only the ReferenceItems Id in the ShoppingItems table to get the Unit Price

是的,你可以。

场景一(无辅助class).

将您在 dao 中的查询更改为如下内容:

@Query("select shoppingItems.*, referenceItems.unitPrice from shoppingItems left join referenceItems on shoppingItems.referenceId=referenceItems.id")
LiveData<List<ShoppingItems>> getShoppingItems()

但要实现这一点 - 您必须在 "shoppingItems" class 中保留 "unitPrice" 字段(当然,您可以在插入数据时将其留空)。您可以尝试使用 @Ignore 注释尝试不将此字段保留在数据库中,但我不能保证在这种情况下查询会 return 价格。

场景二(有辅助class).

所需步骤:

  1. 添加新的辅助class ShoppingItemsWithPrice(这个class不应该在数据库中持久化,所以它没有@Entity)。

    public class ShoppingItemsWithPrice { @Embedded public ShoppingItems shoppingItems; @Relation(parentColumn = "referenceId", entityColumn = "id") public ReferenceItems referenceItems; }

  2. 而你的 DAO 查询:

    @Query("select * from shoppingItems") LiveData<List<ShoppingItemsWithPrice>> getShoppingItemsWithPrice()

因此,查询 returns you object with all you have in both tables。您可以根据 this article

优化它(只获得一个需要的字段)