Prisma、GraphQL和Apollo中具有突变的数据关系和连接类型



很抱歉发了这么长的帖子,但我尽量详细。

我如何编辑我的当前模型、架构和解析器,以便能够通过web表单将相关类型(供应商(保存/连接到我创建的类型(项目(

我想创建一个库存项目,并选择要与该项目关联的供应商。

我有一个类似的Prisma数据模型(为了简单起见,我有其他字段,因为我保存其他字段没有问题;它只是与存在关系的其他类型一起使用(。。。

项目可能有关联的供应商,也可能没有关联的供应商。供应商可能有也可能没有当前与其关联的项目列表。

type Item {
id: ID! @id
name: String!
description: String!
vendor: Vendor
}
type Vendor {
id: ID! @id
items: [Item!]
}

我有一个像这样的graphql模式(与本问题末尾修改的模式相比(。。。

type Mutation {
createItem(
name: String! 
description: String! 
): Item!
}

我的解析器:

async createItem(parent, args, ctx, info) {
const item = await ctx.db.mutation.createItem(
{
data: {
...args,
},
}, info);
return item;
}

我的React组件包含以下内容:

const CREATE_ITEM_MUTATION = gql`
mutation CREATE_ITEM_MUTATION(
$name: String!
$description: String!
) {
createItem(
name: $name
description: $description
) {
id
name
description
vendor {
id
}
}
}
`;
const ALL_VENDORS_QUERY = gql`
query ALL_VENDORS_QUERY {
vendors {
id
}
}
`;

稍后,在我的HTML表单中的网页上,我有:

<Query query={ALL_VENDORS_QUERY}>
{({ data, loading }) => (
<select
id="vendor"
name="vendor"
onChange={this.handleChange}
value={this.state.vendor}
>
<option>Vendor</option>
{data.vendors.map(vendor => (
<option key={vendor.id} value={vendor.id}>{vendor.name}</option>
))}
</select>
)}
</Query>

我只是不知道如何通过表单提交将供应商连接到项目。如果我在解析器中对供应商id进行硬编码,我可以让它正常工作,如下所示:

async createItem(parent, args, ctx, info) {
const item = await ctx.db.mutation.createItem(
{
data: {
vendor: {
connect: { id: "ck7zmwfoxg4b70934wx8kgwkx" } // <-- need to dynamically populate this based on user input from the form
},
...args,
},
}, info);
return item;
}

但那显然不是我想要的。

对我来说,修改我的模式是最有意义的:

createItem(
name: String!
description: String!
vendor: Vendor <--- added
): Item!

但当我这样做的时候,我会得到这个:

Error: The type of Mutation.createItem(vendor:) must be Input Type but got: Vendor.

如何编辑我的当前模型、架构和解析程序,以便能够保存/连接在表单上选择的供应商ID

我的问题在这里找到了答案:如何修复';变量"$_v0_data";得到无效值';由数据类型关系引起-突变解析程序

我在传播args(…args(的同时也传递了vendor参数。

这是我更新的突变:

createItem(
name: String!
description: String!
vendorId: ID
): Item!

及其解析器:

async createItem(parent, {name, description, vendorId}, ctx, info) {
const item = await ctx.db.mutation.createItem(
{
data: {
vendor: {
connect: { id: vendorId }
},
name,
description,
},
}, info);
return item;
}

轰!💥

最新更新