生成唯一的id – doctrine – symfony2

我想为我的门票生成唯一的门票ID。 但是如何让教条生成一个唯一的ID?

/** * @ORM\Column(name="id", type="integer") * @ORM\Id() * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; 

多一点解释:

  • ID必须是6个章程:678915
  • ID必须是唯一的

从版本2.3开始 ,您可以将以下注释添加到您的媒体资源中:

 /** * @ORM\Column(type="guid") * @ORM\Id * @ORM\GeneratedValue(strategy="UUID") */ protected $id; 

使用自定义的GeneratedValue策略:

1.在你的实体类中:

 /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="CUSTOM") * @ORM\CustomIdGenerator(class="AppBundle\Doctrine\RandomIdGenerator") */ protected $id; 

2.然后用内容创build文件AppBundle/Doctrine/RandomIdGenerator.php

 namespace AppBundle\Doctrine; use Doctrine\ORM\Id\AbstractIdGenerator; class RandomIdGenerator extends AbstractIdGenerator { public function generate(\Doctrine\ORM\EntityManager $em, $entity) { $entity_name = $em->getClassMetadata(get_class($entity))->getName(); // Id must be 6 digits length, so range is 100000 - 999999 $min_value = 100000; $max_value = 999999; $max_attempts = $min_value - $max_value; $attempt = 0; while (true) { $id = mt_rand($min_value, $max_value); $item = $em->find($entity_name, $id); if (!$item) { return $id; } // Should we stop? $attempt++; if ($attempt > $max_attempts) { throw new \Exception('RandomIdGenerator worked hardly, but failed to generate unique ID :('); } } } } 

您可以使用PrePersist注释,如下所示:

 /** * @ORM\PrePersist() */ public function preSave() { $this->id = uniqid(); } 

如注释名称所示,它将在对象持久化到数据库之前运行。

对于唯一的ID,我只需使用一个原生的PHP uniqid()函数http://php.net/manual/en/function.uniqid.php ,它将返回13个字符。 要获得只有6个字符,请参阅此PHP票证生成

在$ id属性中,我想你也需要删除这一行来防止自动生成的值:

 @ORM\GeneratedValue(strategy="AUTO") 

学说将把这个字段当作你的主键(因为@Id注释),所以这个字段已经是唯一的了。 如果你在AUTO策略上有@GeneratedValue注解,Doctrine会找出在db平台上使用dependend的策略。 它将在MySql上默认为IDENTITY ,然后该字段将成为auto_increment

您可以编写不带括号的id注释,如下所示。

  • ORM \标识

当我借用Jonhathan所build议的UUID方法时,您可能更喜欢更短,更易读的标识符。 在这种情况下,您可以使用ShortId Doctrine包 。