级联协会

时间:2013-03-19 06:27:57

标签: symfony

我正在尝试embed a collection of forms,但我无法持久保存新创建的对象。

Customer有很多Email个。在我的控制器中,

// 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();

它增加了客户,但是当它试图添加电子邮件时,它说没有设置customerId。所以,我试过这个,它的确有效:

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对象(我知道它可以)。

1 个答案:

答案 0 :(得分:1)

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

此方法应如下所示:

public function addEmail($email)
{
  $email->setCustomer($this);
  $this->emails[] = $email;
  return $this;
}