如何同步Amplify DataStore和DynamoDB之间的一对多关系?

问题描述

我正在使用两种型号的食品杂货清单应用程序:产品食品杂货清单。杂货列表中有很多产品,而一个商品属于一个杂货列表。

# schema.graphql
type Product @model 
{
  id: ID!
  groceryList: GroceryList @connection(name: "GroceryListProducts")
  name: String!
}

type GroceryList @model {
  id: ID!
  name: String!
  products: [Product] @connection(name: "GroceryListProducts")
}

据我了解,在DynamoDB上,可以使用全局二级索引查询一对多关系,而不会直接显示在DynamoDb记录上:

DynamoDB杂货清单列表:

╔═══════╦═════════╗
║ Id    ║    Name ║
╠═══════╬═════════╣
║ L1    ║ List1   ║ 
║ L2    ║ List2   ║
║ L3    ║ List3   ║ 
╚═══════╩═════════╝

DynamoDB产品列表表:

╔═════════╦═══════╦════════╗
║ Id      ║ Name  ║ PID*   ║
╠═════════╬═══════╬════════╣
║ O1      ║ Orange║ L1     ║
║ O2      ║ Apple ║ L1     ║
║ O3      ║ Bacon ║ L2     ║
╚═════════╩═══════╩════════╝

* ProductGroceryListId

当我添加产品并将其保存到DataStore时,如下所示:

      const productSaved = await DataStore.save(
        new Product(product)
      )
      await DataStore.save(
        GroceryList.copyOf(currentList,updated => {
          updated.products = [...updated.products,productSaved]
    }))

数据存储区上的GroceryList实例将正确显示产品子级:

// GroceryList item showing on the browser DevTools,tab Application,IndexDB,amplify DataStore:
{
 id: "L1"
 name: "List1"
 products: [
  {id: "01",groceryList: {…},name: "Orange"},{id: "02",name: "Apple"}
 ]
}

但是,如果我添加了与Cloud的同步:

 const subscription = DataStore.observe(Product).subscribe(msg => {
        console.log(msg.model,msg.opType,msg.element);
})

这些子项将从GroceryList DataStore实例中消失。 如何防止它发生?

我想确保可以在线和离线使用我的应用程序。

预先感谢您的帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)