【问题标题】:Symfony2 - ReferencedColumnName id is nullSymfony2 - ReferencedColumnName id 为空
【发布时间】:2014-12-30 18:49:31
【问题描述】:

我将关闭 form collections 上的食谱文章,但是当尝试将其持久化到数据库时,我收到了一个约束违反错误,并且引用的列名称 id 为空。

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null

我相信实体设置正确且关联正确,我需要在表单中添加一些我缺少的东西吗?

客户

/**
 * @ORM\OneToMany(targetEntity="ClientPhone", mappedBy="clients", cascade={"persist"})
 */
protected $clientphones;

客户电话

/**
 * @ORM\ManyToOne(targetEntity="Client", inversedBy="clientphones")
 * @ORM\JoinColumn(name="client_id", referencedColumnName="id", nullable=false)
 */
protected $clients;

客户端类型表单

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('firstName', 'text', array(
            'label' => 'First Name'
    ))
        ->add('lastName', 'text', array(
            'label' => 'Last Name'
    ))
        ->add('email', 'text', array(
            'label' => 'E-mail Address'
    ))
        ->add('clientphones', 'collection', array(
            'type'         => new ClientPhoneType(),
            'allow_add'    => true,
            'allow_delete' => true,
            'by_reference' => false,
    ));
}

ClientPhoneType 表单

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('home', 'text');
    $builder->add('office', 'text');
    $builder->add('mobile', 'text');
}

客户端控制器

$client = new Client();

    $phone = new ClientPhone();
//        $phone->home   = '2134959249';
//        $phone->office = '2134959249';
//        $phone->mobile = '2134959249';
    $client->getClientPhones()->add($phone);

    $form = $this->createForm(new ClientType(), $client, array(
        'action' => $this->generateUrl('client'),
        'method' => 'POST',
    ));
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $em->persist($client);
        $em->flush();

        $session = $request->getSession();
        $session->getFlashBag()->add('message', 'Client successfully saved to database');

        return $this->redirect($this->generateUrl('client'));
    }

【问题讨论】:

    标签: forms symfony doctrine-orm formcollection


    【解决方案1】:

    找出问题所在。问题出在addClientphone 函数中的客户端实体上。我不得不更改预生成的代码:

    $this->clientphones[] = $clientphones;
    

    致以下:

    if (!$this->clientphones->contains($clientphone)) {
            $clientphone->setClients($this);
            $this->clientphones->add($clientphone);
        }
    
        return $this->clientphones;
    

    【讨论】:

    • 这是一个记录在案的问题 -- Doctrine2 只有在关联的 owning 端设置新关联时才会保留它。在这种情况下,$clientphone 是拥有方,每当您将 $clientphone 添加到 $client 时,您还需要将 $client 添加到 $clientphone。不需要反过来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多