我为调查创建了三个相关实体:Question
,Options
和Answer
。
/**
* @ORM\Entity(repositoryClass="App\Repository\QuestionRepository")
*/
class Question
{
// ...
/**
* @ORM\OneToMany(targetEntity="App\Entity\Answer", mappedBy="question")
*/
private $answers;
/**
* @Groups({"question"})
* @ORM\OneToMany(targetEntity="App\Entity\Options", mappedBy="question")
*/
private $options;
public function __construct()
{
$this->options = new ArrayCollection();
$this->answers = new ArrayCollection();
}
// ...
}
/**
* @ORM\Entity(repositoryClass="App\Repository\OptionsRepository")
*/
class Options
{
// ...
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="options")
* @ORM\JoinColumn(nullable=false)
*/
private $question;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Answer", mappedBy="options")
*/
private $answers;
public function __construct()
{
$this->answers = new ArrayCollection();
}
// ...
}
/**
* @ORM\Entity(repositoryClass="App\Repository\AnswerRepository")
*/
class Answer
{
// ...
/**
* @Assert\NotBlank()
* @Groups({"answer"})
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="answers")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @Groups({"answer"})
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $text;
/**
* @Groups({"answer"})
* @ORM\ManyToMany(targetEntity="App\Entity\Options", inversedBy="answers")
*/
private $options;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="answers")
* @ORM\JoinColumn(nullable=false)
*/
private $question;
public function __construct()
{
$this->options = new ArrayCollection();
}
// ...
}
App \ Form \ AnswerType:
class AnswerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('text')
->add('user')
->add('question')
->add('options', EntityType::class, [
'class' => Options::class,
'multiple' => true
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Answer::class,
'csrf_protection' => false
]);
}
}
我需要将调查结果保存到Answer
实体。
我该如何处理这个职位要求?该查询将在表单提交时发送。每个Answer
行都是一个嵌套的JSON对象。
[
{
"question": "1",
"user": "1",
"text": "",
"options": [
"1",
"2",
"3"
]
},
{
"question": "2",
"user": "1",
"text": "text",
"options": [
""
]
},
{
"question": "3",
"user": "1",
"text": "",
"options": [
"4"
]
}
]
因此,此嵌套的JSON对象(问题,用户,文本,选项)中的每一个都应成为Answer表中的一行。我的意思是json question
对象的属性应该在question_id
表的Answer
列中进行,等等。