You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Amplify+Flutter中@manyToMany创建与查询问题求助

多对多关联创建修正与查询方案

一、GraphQL Schema 正确性确认

你的Schema中@manyToMany的定义是正确的:

  • Branch和User双向配置了相同关联名称的@manyToMany(relationName: "BranchesUsers"),Amplify会自动生成中间表BranchesUsers维护多对多关系。

二、Flutter 关联创建代码修正

当前_createAssociationUserBranch方法存在两个核心问题:

  1. 更新User和Branch时,错误地将中间表实体BranchesUsers赋值给branches/users字段(这两个字段类型是[Branch]/[User],而非中间表类型)
  2. 手动更新主实体属于冗余操作,Amplify通过中间表即可维护多对多关联,无需额外更新

修正后的_createAssociationUserBranch方法:

Future<void> _createAssociationUserBranch(Branch branch, User user) async {
  // 直接创建中间表关联实体即可,无需手动更新User和Branch
  BranchesUsers branchesUsers = BranchesUsers(
    branchId: branch.id,
    userId: user.id
  );

  GraphQLRequest<BranchesUsers> branchUserRequest = ModelMutations.create(branchesUsers);
  final branchUserResponse = await Amplify.API.mutate(request: branchUserRequest).response;
  
  if (branchUserResponse.data == null) {
    safePrint('errors: ${branchUserResponse.errors}');
    Amplify.Auth.signOut();
    throw ApiException("Critical error");
  }
}

另外,createAccount方法中创建newOrganization时,不要直接传入未创建的branches和users参数(关联会失效),修正后:

Organization newOrganization = Organization(
  id: organization.id,
  organizationName: "",
  owner: user
);

三、多对多关系查询方法

1. 查询指定User关联的所有Branch

使用ModelQueries.get并通过include参数加载关联数据:

Future<List<Branch>?> getUserBranches(String userId) async {
  final request = ModelQueries.get(
    User.classType,
    userId,
    include: const [User.BRANCHES]
  );
  
  final response = await Amplify.API.query(request: request).response;
  final user = response.data;
  return user?.branches;
}

2. 查询指定Branch关联的所有User

同理,查询Branch时加载关联的users:

Future<List<User>?> getBranchUsers(String branchId) async {
  final request = ModelQueries.get(
    Branch.classType,
    branchId,
    include: const [Branch.USERS]
  );
  
  final response = await Amplify.API.query(request: request).response;
  final branch = response.data;
  return branch?.users;
}

3. 列表查询时包含关联数据

查询多个User并同时加载他们的Branch:

Future<void> listUsersWithBranches() async {
  final request = ModelQueries.list(
    User.classType,
    include: const [User.BRANCHES]
  );
  
  final response = await Amplify.API.query(request: request).response;
  final users = response.data?.items;
  if (users != null) {
    for (var user in users) {
      print("User ${user.userFullName} belongs to branches: ${user.branches?.map((b) => b.branchName)}");
    }
  }
}

四、额外注意事项

  • 修改Schema后,必须运行amplify codegen models重新生成Flutter实体类(包括BranchesUsers)
  • 当前代码未实现事务回滚,若某一步失败,需手动删除已创建的实体,可考虑使用Amplify批量操作或自定义事务逻辑

内容的提问来源于stack exchange,提问作者Higuchi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:35:51