我在数据库中有两个表。球队和联赛。通过Apollo,我有一个CREATE_TEAM_MUTATION来保存到数据库,还有一个ALL_LEAGUES_QUERY来检索每个联赛名称,以便将选项填充为表格中的一个选择。
但是当我保存时,出现错误:
变量“ $ _v0_data”的值无效{{league“:”“,” name“:” Sample Team“,” number“:1};预期类型LeagueCreateOneInput是value.league的对象。
我正在尝试了解此处的数据流。我的意图是将所选联赛的ID保存为teams表中每个团队的列条目(联盟)。
这是我在后端的棱镜数据模型
type League {
id: ID! @unique
name: String!
description: String
}
type Team {
id: ID! @unique
name: String!
number: Int!
league: League
}
这是我在后端的createTeam Mutation:
async createTeam(parent, args, ctx, info) {
// create the user in the database
const team = await ctx.db.mutation.createTeam(
{
data: {
league: {
connect: {
id: ctx.request.leagueId
}
},
...args,
},
},
info
);
return team;
},
这是我从前端进行的查询和更改:
const CREATE_TEAM_MUTATION = gql`
mutation CREATE_TEAM_MUTATION(
$name: String!
$number: Int
$league: String
) {
createTeam(
name: $name
number: $number
league: $league
) {
id
}
}
`;
const ALL_LEAGUES_QUERY = gql`
query ALL_LEAGUES_QUERY {
leagues {
id
name
description
}
}
`;
这是我的render():
render() {
return (
<Mutation mutation={CREATE_TEAM_MUTATION} variables={this.state}>
{(createTeam, { loading, error }) => (
<Form
onSubmit={async e => {
// Stop the form from submitting
e.preventDefault();
// call the mutation
const res = await createTeam();
// change them to the single team page
console.log(res);
Router.push({
pathname: '/team',
query: { id: res.data.createTeam.id },
});
}}
>
<Error error={error} />
<fieldset disabled={loading} aria-busy={loading}>
<label htmlFor="name">
Name
<input
type="text"
id="name"
name="name"
placeholder="Team Name"
required
value={this.state.name}
onChange={this.handleChange}
/>
</label>
<label htmlFor="number">
Number
<input
type="number"
id="number"
name="number"
placeholder="Team Number"
value={this.state.number}
onChange={this.handleChange}
/>
</label>
<label htmlFor="league">
League
<Query query={ALL_LEAGUES_QUERY}>
{({ data, error, loading }) => {
console.log('data', data);
if (loading) return <p>Loading...</p>
if (error) return <p>Error... {error.message}</p>
return (
<select id="league"
name="league"
value={this.state.league}
onChange={this.handleChange}>
{data.leagues.map((league) => (
<option key={league.id} value={league.id}>{league.name}</option>
))}
</select>
)
}}
</Query>
</label>
<button type="submit">Create Team</button>
</fieldset>
</Form>
)}
</Mutation>
);
}
答案 0 :(得分:0)
感谢Slack论坛中的几个人,终于找到了答案。将其发布在这里,希望对其他遇到相同问题的人有所帮助:
这是旧代码:
async createTeam(parent, args, ctx, info) {
// create the user in the database
const team = await ctx.db.mutation.createTeam(
{
data: {
league: {
connect: {
id: ctx.request.leagueId
}
},
...args,
},
},
info
);
return team;
},
这是新的:
const params = {...args};
delete params.league;
const team = await ctx.db.mutation.createTeam(
{
data: {
league: {
connect: {
id: args.league
}
},
...params
},
},
info
);
return team;
},
所以您看到我有两个问题。
首先,id: ctx.request.leagueId 必须是 id:id:args.league
第二,我两次进入联赛。一次通过连接,再一次通过... args传播。那是真正导致错误的原因。因此,使params为var,将其传递给args传播,然后从params中删除同盟,然后它就起作用了。