Flutter应用中如何按指定Recipe ID同步关联Ingredient数据
解决方案:同步特定Recipe关联的Ingredient数据
在Amplify DataStore中处理多对多关联的选择性同步时,不能直接通过Ingredient.RECIPES.contains()嵌套关联条件,需要借助自动生成的中间表RecipeIngredient来构建正确的同步表达式。
正确的同步配置代码
替换你原有的AmplifyDataStore配置部分,使用以下同步表达式:
await Future.wait([ Amplify.addPlugin(AmplifyDataStore( modelProvider: ModelProvider.instance, syncExpressions: [ DataStoreSyncExpression( Ingredient.classType, () => RecipeIngredient.INGREDIENT.eq( IngredientModelIdentifier(id: Ingredient.ID) ).and( RecipeIngredient.RECIPE.eq(RecipeModelIdentifier(id: recipeId)) ), syncMode: SyncMode.syncWithSubscription, ), ], )), Amplify.addPlugin(AmplifyAPI()), Amplify.addPlugin(AmplifyAuthCognito()), Amplify.addPlugin(AmplifyStorageS3()), ]); await Amplify.configure(amplifyconfig);
关键说明
- 多对多关系会自动生成
RecipeIngredient中间表,我们通过该表的INGREDIENT字段关联到Ingredient的ID,同时筛选RECIPE字段等于目标recipeId,以此精准定位关联的Ingredient数据。 - 若之前已有本地同步数据,建议先调用
Amplify.DataStore.clear()清除本地存储,再重新配置同步,避免旧数据残留导致筛选异常。
验证同步结果
配置完成后,调用DataStore查询Ingredient即可获取仅与目标Recipe关联的数据:
final ingredients = await Amplify.DataStore.query( Ingredient.classType, );
内容的提问来源于stack exchange,提问作者tamptek
相关产品推荐
相关产品推荐

