在我的 Symfony 4 项目中,我有 2 个实体:问题和可能的答案。
一个问题可以有许多可能的答案,一个答案可以用于许多不同的问题。
我想发布一个问题,我使用 FOSRestBundle
。
这是我格式化请求正文的方式:
{
"title": "my question",
"possibleAnswers": [
{
"id": 1,
"title": "my first answer"
}
]
}
至少这是当我直接在数据库中创建数据并获取问题时 FOSRestBundle 格式化答案的方式。
但我不断收到同样的错误:
Validation Failed, possibleAnswers This value is not valid
我使用 Symfony 表单来验证我的 POST,并且我用于问题的 possibleAnswers 字段的 fieldType 是一个 EntityType,其选项 multiple 设置为 true。也许这就是错误的来源。
所以我的问题是:
如何格式化请求正文以添加有效的 possibleAnswers 字段?如果我做得对,我应该使用哪种表单类型才能使其正常工作?
抱歉没有添加任何代码,上下文实际上相当复杂,但我很确定我的字段的 JSON 格式或表单类型是错误的。
[编辑]
这里是我为可能的答案字段尝试过的所有表单类型
//->add('possibleAnswers', EntityType::class, array('data' => [], 'required' => false, 'multiple' => true, 'class' => PossibleAnswer::class))
->add('possibleAnswers', CollectionType::class, array('required' => false, 'entry_type' => EntityType::class, 'entry_options' => array('class' => PossibleAnswer::class)))
//->add('possibleAnswers', CollectionType::class, array('required' => false, 'entry_type' => PossibleAnswerType::class))
//->add('possibleAnswers', CollectionType::class, array('required' => false, 'entry_type' => PossibleAnswerType::class, 'entry_options' => array('class' => PossibleAnswer::class)))
以下是我尝试选择可能答案的所有 JSON 格式:
{
"title": "a postman created question",
"answerConditions": [
{
"id": 1,
"title": "already existing question",
}
]
}
{
"title": "a postman created question",
"answerConditions": [
{
"possibleanswer_id": 1
}
]
}
{
"title": "a postman created question",
"answerConditions": [
{
"id": 1
}
]
}
{
"title": "a postman created question",
"answerConditions": [
1
]
}
最佳答案
如果您想在发布问题时创建可能的答案,则需要将表单中的 EntityType 替换为 CollectionType。
当我想在发布父对象(问题)时发布子对象(此处为可能的答案)时,我经常在 POST 请求中使用它:
问题表
$builder
->add('possibleAnswers', CollectionType::class, array(
'entry_type' => PossibleAnswerType::class,
'allow_add' => true,
))
;
可能的答案形式:
$builder
->add('title')
;
json 看起来像:
{
"title": "my question",
"possibleAnswers": [
{
"title": "my first answer"
}
]
}
希望对你有帮助。
编辑: 如果您想在创建问题时将可能的答案链接到问题,您可以使用以下命令:
问题形式:
$builder
->add('possibleAnswer', EntityType::class, array(
'class' => YOUR_ENTITY::class,
'multiple' => true
));
你的 json 应该只包含你想要链接到的实体的 id。应该是这样的:
{
"title": "a postman created question",
"answerConditions": [
1
]
}
关于json - 休息API : how to post a manytomany relationship with fosrestbundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48909265/