我正在开发一个使用Auth0,Hasura / PostgreSQL,GraphQL和Apollo的React应用,我非常环保,因此显然我需要一些帮助。以下是我要实现的目标:
用户提交表单以创建新团队。该记录已添加到“团队”表中,现在我需要返回该ID,以便在“ teamstaff”表中创建一行。
表结构:
import gql from "graphql-tag";
const insertTeam = gql `
mutation ($name: String!, $gender: String!, $birth_year: Int!, $created_by: String!) {
insert_teams(objects: {name: $name, gender: $gender, birth_year: $birth_year, created_by: $created_by}) {
affected_rows
returning {
id
name
gender
birth_year
created_by
}
}
}
`;
export default insertTeam;
我能够向数据库中添加一个新团队,但是我需要从该新创建的团队获取ID的帮助,因此我可以在“ teamstaff”表中创建初始记录。另外,有没有更好的方法来构造我的桌子?每个用户都可以分配到多个团队,每个团队的角色不同。
答案 0 :(得分:0)
我不确定您如何执行此突变,但是我假设您正在使用Apollo的Mutation Component。这是如何获取最近添加的记录的ID的示例:
import React from "react";
import gql from "graphql-tag";
import { Mutation } from "react-apollo";
const INSERT_TEAM = gql `
mutation InsertTeam($name: String!, $gender: String!, $birthYear: Int!, $createdBy: String!) {
insertTeam(objects: {name: $name, gender: $gender, birthYear: $birthYear, createdBy: $createdBy}) {
affectedRows
returning {
id
name
gender
birthYear
createdBy
}
}
}
`;
const onInsertTeamCompleted = ({ insertTeam }) => {
console.log(insertTeam.returning.id); // Here you have your ID
}
const Screen = () => (
<Mutation mutation={INSERT_TEAM} onCompleted={onInsertTeamCompleted}>
{(insertTeam, { data }) => { // Through data, you can also access data.insertTeam results.
const onInserTeam = () => {
insertTeam({ variables: {name: "Mary", gender: "Female", birthYear: 1990} });
};
return (
<button onClick={onInserTeam}>Insert demo team</button>
);
})}
</Mutation>
)
export default Screen;
您可能已经注意到,我已经更新了查询,以遵循属性的命名约定(是,使用camelCase),但是此更改对最终结果没有影响。
如果您还没有读过它,那么Apollo文档中的Mutation Component section讨论了许多重要的事情,例如更新缓存和处理错误,因此这是必读的! ?
答案 1 :(得分:0)
我知道这个问题很旧,但是Hasura会为您解决这个问题(此时)。 您只需要在User_Id字段中提供关系的一侧
mutation($name: String!, $gender: String!, $birth_year: Int!, $created_by: String, $user_id: String!) {
insert_teams(
objects: {
TeamStaff: {
data: {
User_Id: $user_id
}
},
name: $name,
gender: $gender,
birth_year: $birth_year,
created_by: $created_by }
) {
affected_rows
returning {
id
name
gender
birth_year
created_by
}
}
}