生成唯一的id - doctrine - symfony2

Mit*_*oof 37 doctrine symfony

我想为我的门票生成唯一的门票ID.但是如何让学说产生一个独特的身份?

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

更多解释:

  • id必须是6个章程,如:678915
  • id必须是唯一的

Jon*_*han 68

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

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


psy*_*sss 38

使用自定义GeneratedValue策略:

1.在您的实体类中:

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

2.然后创建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);

            // Look in scheduled entity insertions (persisted queue list), too
            if (!$item) {
                $persisted = $em->getUnitOfWork()->getScheduledEntityInsertions();
                $ids = array_map(function ($o) { return $o->getId(); }, $persisted);
                $item = array_search($id, $ids);
            }

            if (!$item) {
                return $id;
            }

            // Should we stop?
            $attempt++;
            if ($attempt > $max_attempts) {
                throw new \Exception('RandomIdGenerator worked hardly, but failed to generate unique ID :(');
            }  
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如何处理碰撞?在Web应用程序中,在db中刷新生成的id之前,可能是另一个请求已生成并刷新了相同的id.有更强大的解决方案吗? (2认同)