在创建表单中无法关联相关项目的一个可能原因是关联关系定义不正确。请确保在schema中正确定义了对象之间的关联关系。具体定义方法可参考以下代码示例:
type Post @model {
id: ID!
title: String!
comments: [Comment] @connection(keyName: "byPost", fields: ["id"])
}
type Comment @model {
id: ID!
content: String!
post: Post @connection(keyName: "byPost", fields: ["id"])
}
在上面的示例中,我们定义了一个post对象和一个comment对象,并通过@connection指令将它们关联起来,其中keyName是一个唯一值,用于标识关联关系。通过设置fields属性,我们定义了关联关系的约束条件。
在创建项目时,我们可以使用关联关系ID来关联相关的项,在Amplify with React中通常使用uuid来生成ID。我们可以在创建表单中添加一个关联关系ID字段,并将其设置为隐藏字段,然后在提交表单时将其设置为输入的关联关系ID。以下是一个示例代码:
import React, { useState } from 'react'
import { v4 as uuid } from 'uuid'
import { API, graphqlOperation } from 'aws-amplify'
import { createPost } from './graphql/mutations'
function CreatePost() {
const [title, setTitle] = useState('')
const [commentId, setCommentId] = useState(uuid())
async function handleSubmit(event) {
event.preventDefault()
const input = {
title,
comments: {
connect: { id: commentId }
}
}
await API.graphql(graphqlOperation(createPost, { input }))
}
return (
)
}
export default CreatePost
在上面的示例中,我们在表单中添加了一个隐藏字段“commentId”,并为其赋