0

我正在尝试嵌入表单集合,但在持久化新创建的对象时遇到了麻烦。

ACustomer有很多Emails。在我的控制器中,

// 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对象(据我所知)。

4

1 回答 1

1

尝试更改 Customer 类中的默认“addEmail”方法。

此方法应如下所示:

public function addEmail($email)
{
  $email->setCustomer($this);
  $this->emails[] = $email;
  return $this;
}
于 2013-03-19T10:39:16.043 回答