Doctrine2 - 在刷新之前,列变为null

时间:2013-04-19 08:41:35

标签: php symfony orm doctrine-orm

我正在尝试在数据库中插入新的对象/行。该对象的创建方式如下:

$nodeaccess = new Nodeaccess(); // A by doctrine2 generated entity
$nodeaccess->setAccesslevel(0);
$nodeaccess->setDraw(0);
$nodeaccess->setUserid($userid);
$nodeaccess->setNodename($this->getUser()->getUsername() . ' Node');
$nodeaccess->setMac($node);

已设置表格的所有列。当我打印$nodeaccess->getUserid()$nodeaccess->getMac()时,会打印所需的结果。它们都不为空

但是当对象持久存在时:

$em = $this->getDoctrine()->getManager();
$em->persist($nodeaccess);
$em->flush();

发生以下错误:

  

执行'INSERT INTO nodeaccess时发生异常(mac,   userID,accessLevel,nodeName,draw)VALUES(?,?,?,?,?)'   params {“1”:null,“2”:null,“3”:0,“4”:“示例节点”,“5”:0}:

     

SQLSTATE [23000]:完整性约束违规:1048列'mac'   不能 null

组合的mac和userID是主键,它们都是外键。 它们在模型中设置如下:

/**
 * @var integer
 *
 * @ORM\Column(name="mac", type="bigint", nullable=false)
 * @ORM\Id
 */
private $mac;

/**
 * @var integer
 *
 * @ORM\Column(name="userID", type="integer", nullable=false)
 * @ORM\Id
 **/
private $userid;

公共访问者已实施,我已尝试将字段更改为公开,但没有帮助。

更新 访问者:

public function getMac()
{
    return $this->mac;
}

public function setMac($mac)
{
    $this->mac = $mac;
}

public function getUserid()
{
    return $this->userid;
}

public function setUserid($userid)
{
    $this->userid = $userid;
}

更新2 我已经更改了表,现在只有mac字段为NULL。 新模式:

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var integer
 *
 * @ORM\Column(name="mac", type="bigint", nullable=false)
 */
private $mac;

/**
 * @var integer
 *
 * @ORM\Column(name="userID", type="integer", nullable=false)
 **/
private $userid;

更新控制器操作:

public function inviteAction() {
    $repository = $this->getDoctrine()
            ->getRepository('GeninnoEDSBundle:Nodeaccess');
    $options = $repository->createQueryBuilder('na')
            .......
            ->getQuery()
            ->getResult();

    $form = $this->createFormBuilder()
            ->add('user', 'text', array(
                'attr' => array(
                    'placeholder' => '+ Gebruiker'
                )
            ))
            ->add('node', 'hidden')
            ->getForm();

    if ($this->getRequest()->isMethod('POST')) {
        $form->bind($this->getRequest());

        if ($form->isValid()) {
            $data = $form->getData();

            $user_repository = $this->getDoctrine()
                    ->getRepository('GeninnoEDSBundle:User');
            $user = $user_repository->findOneBy(array('username' => $data['user']));

            $node_repository = $this->getDoctrine()
                    ->getRepository('GeninnoEDSBundle:Node');
            $node = $node_repository->find($data['node']);

            $nodeaccess = new Nodeaccess();
            $nodeaccess->setAccesslevel(0);
            $nodeaccess->setDraw(0);
            $nodeaccess->setUserid($user);
            $nodeaccess->setNodename($this->getUser()->getUsername() . ' Node');
            $nodeaccess->setMac($node);

            $em = $this->getDoctrine()->getManager();
            $em->persist($nodeaccess);
            $em->flush();
        }
    }

    return array('options' => $options, 'form' => $form->createView());
}

2 个答案:

答案 0 :(得分:1)

通过重新生成这个特定的实体已经解决了这个问题(哦哦)。字段已更改为:

/**
 * @var \User
 *
 * @ORM\ManyToOne(targetEntity="User")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="userID", referencedColumnName="id")
 * })
 */
private $userid;

/**
 * @var \Node
 *
 * @ORM\ManyToOne(targetEntity="Node")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="mac", referencedColumnName="mac")
 * })
 */
private $mac;

<强>更新

这可能不是我认为的解决方案。在将一些字段添加回类后再次出现问题。我发现通过删除以下代码,用户在持久化时不再被赋值为null。

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToOne(targetEntity="User", inversedBy="accessNodes")
 * @ORM\JoinColumn(name="userID", referencedColumnName="id")
 **/
private $accessUsers;

答案 1 :(得分:0)

简答:节点的隐藏表单字段使用__toString()值,该值不是id,因此您的存储库调用将无法找到它,因此在持续时间内为null。

长答案:使用变压器:

在您的控制器中:

use GeninnoEDSBundle\Transformer\NodeTransformer;

修改表单构建器:

$transformer = new NodeTransformer( $em );
$form = $this->createFormBuilder()
        ->add('user', 'text', array(
            'attr' => array(
                'placeholder' => '+ Gebruiker'
            )
        ))
        ->add($builder->create( 'node', 'hidden')
            ->addModelTransformer( $transformer )
        )
        ->getForm();

您的变压器(新文件:GeninnoEDSBundle \ Transformer \ NodeTransformer.php):

<?php

namespace GeninnoEDSBundle\Transformer;

use Doctrine\Common\Persistence\ObjectManager;
use GeninnoEDSBundle\Entity\Node;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

class NodeTransformer implements DataTransformerInterface
{
    /**
    * @var ObjectManager
    */
    private $em;

    //  If selector is multiple (Many2One or Many2Many)

    private $multi;

    /**
    * @param ObjectManager $em
    */
    public function __construct(ObjectManager $em, $multi=false)
    {
        $this->em = $em;
        $this->multi=$multi;
    }

    /**
    * Transforms an object (node) to a string (id).
    *
    * @param  Issue|null $node
    * @return string
    */
    public function transform($node)
    {
        if (null === $node) {return "";}
        if (is_object($node) && method_exists($node, "toArray")){
            $node=$node->map(function ($ob){return $ob->getId();});
            return implode(",",$node->toArray());
        }

        if ('array' == gettype($node)) {
            return implode(','
                          , array_map(function($element){
                                          return $element->getId();
                                      }
                                      ,$node));
        }
// var_dump($node);
        return $node->getId();
    }

    /**
    * Transforms a string (id) to an object (node).
    *
    * @param  string $id
    * @return Issue|null
    * @throws TransformationFailedException if object (node) is not found.
    */
    public function reverseTransform($id)
    {

        if (!$id) {
            if($this->multi) {return array();}
            return null;
        }

        if (strpos($id,',') !== false) {
            $id=explode(',',$id);
        }

        $qb=$this->em
        ->getRepository('GeninnoEDSBundle:Node')
        ->createQueryBuilder('r');
        $qb->andWhere($qb->expr()->in('r.id', $id));
        if (is_array($id) || $this->multi){
            $node=$qb->getQuery()
            ->getResult();
        } else {
            $node=$qb->getQuery()
            ->getSingleResult();
        }

        if (null === $node) {
            throw new TransformationFailedException(sprintf(
                'An node with id "%s" does not exist!',
                $id
                ));
        }

        return $node;
    }
}

请注意:我已经添加了变压器,但您可能需要为您的应用程序添加逻辑。

有关变形金刚的更多信息:http://symfony.com/doc/current/cookbook/form/data_transformers.html