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

Amplify/React中GraphQL多表@hasMany关联的增改实现问题

解决Amplify GraphQL @hasMany关联的增改问题

错误原因解析

你遇到的"The variables input contains a field name 'children' that is not defined for input object type 'UpdateUserInput'"错误,本质是Amplify对@hasMany关联的维护逻辑和你理解的不同:

  • @hasMany是基于子表外键的关联,父表(User)不会存储子表(Child)的ID列表;
  • 关联关系由子表的自动生成外键(比如Child表的userId字段,由@belongsTo自动生成)维护;
  • Amplify生成的UpdateUserInput不会包含children字段,所以直接更新User的children字段无效。

正确解决方案

方案1:创建Child时直接关联User

在创建Child的同时,传入父级User的ID(通过自动生成的userId字段),一步完成关联:

async function createChildinDB(childAge, childName, childCommonNoun, userID) {
    const data = {
      age: childAge,
      name: childName,
      commonNoun: childCommonNoun,
      userId: userID // 关键:传入User的ID,建立关联
    };

    const childCreationResponse = await API.graphql({
      query: createChild,
      variables: { input: data },
      authMode: "AMAZON_COGNITO_USER_POOLS"
    }).then(response => {
      console.log(response);
      return response;
    }).catch(e => {
        console.log(e);
        return null;
    });

    return(childCreationResponse);
}

方案2:为已创建的Child关联User

如果已经单独创建了Child,只需更新Child的userId字段即可关联到目标User:

export async function associateChildToUser(childId, userId) {
  const data = {
    id: childId,
    userId: userId // 更新子表的外键,关联到指定User
  };

  const updateChildResponse = await API.graphql({
    query: updateChild,
    variables: { input: data },
    authMode: "AMAZON_COGNITO_USER_POOLS"
  }).then(response => {
    console.log(response);
    return response;
  }).catch(e => {
    console.log(e);
    return null;
  });

  return updateChildResponse;
}

验证关联是否生效

可以通过嵌套查询,获取User及其关联的Child列表,验证关联是否成功:

export async function getUserWithChildren(userId) {
  const query = `
    query GetUser($id: ID!) {
      getUser(id: $id) {
        id
        email
        children {
          items {
            id
            name
            age
          }
        }
      }
    }
  `;

  const response = await API.graphql({
    query,
    variables: { id: userId },
    authMode: "AMAZON_COGNITO_USER_POOLS"
  });

  return response.data.getUser;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:11:09