我正在尝试嵌入表单集合,但在持久化新创建的对象时遇到了麻烦。
ACustomer
有很多Email
s。在我的控制器中,
// CustomersController.php
$customer = new Customer();
$customer->setCreatedBy(0);
$blankEmail = new Email();
$customer->addEmail($blankEmail);
$form = $this->createForm(new CustomerType(), $customer);
我确实记得在Customer
课堂上设置了级联选项:
// Customer.php
...
/**
* @ORM\OneToMany(targetEntity="Email", mappedBy="customer", cascade={"persist"})
*/
protected $emails;
我的Email
班级也有所需的信息:
// Email.php
...
/**
* @ORM\ManyToOne(targetEntity="Customer", inversedBy="emails", cascade={"persist"})
* @ORM\JoinColumn(name="customers_id", referencedColumnName="id")
*/
protected $customer;
由于某种原因,这不起作用:
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($customer);
$em->flush();
它可以添加客户,但是当它尝试添加电子邮件时,它说没有设置客户 ID。所以,我尝试了这个,它有效:
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
foreach ($customer->getEmails() as $email)
$email->setCustomer($customer);
$em->persist($email);
}
$em->persist($customer);
$em->flush();
但我真的很希望能够一举获得它,只需坚持$customer
对象(据我所知)。