Wygeneruj unikalny id - doctrine-symfony2

Chcę wygenerować unikalny identyfikator biletu dla moich biletów. Ale jak pozwolić doktrynie wygenerować unikalny identyfikator?

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

Trochę więcej wyjaśnij:

  • id musi być 678915
  • id musi być unikalne
Author: BenMorel, 2013-02-23

5 answers

Począwszy od wersji 2.3 , możesz po prostu dodać następujące adnotacje do swojej nieruchomości:

/**
 * @ORM\Column(type="guid")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="UUID")
 */
protected $id;
 71
Author: Jonathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-05 17:04:25

Użyj niestandardowej strategii GeneratedValue:

1. w klasie encji:

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

2. następnie utwórz plik AppBundle/Doctrine/RandomIdGenerator.php z zawartością

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 :(');
            }  
        }

    }
}
 39
Author: psylosss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-25 14:26:51

Możesz użyć adnotacji PrePersist, w następujący sposób:

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

Jak sugeruje nazwa adnotacji, zostanie ona uruchomiona przed object persistence do bazy danych.

Dla unikalnego id, po prostu używam natywnej funkcji php uniqid () http://php.net/manual/en/function.uniqid.php który zwróci 13 znaków. Aby uzyskać tylko 6 znaków, zapoznaj się z tym PHP Ticket ID Generation

We właściwości $id, myślę, że musisz również usunąć tę linię, aby zapobiec automatycznemu generowaniu wartość:

@ORM\GeneratedValue(strategy="AUTO")
 3
Author: ihsan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:22

Doctrine potraktuje to pole jako klucz główny (ze względu na adnotację @Id), więc to pole jest już unikalne. Jeśli posiadasz @GeneratedValue adnotację na AUTO Strategy Doctrine, dowiesz się, którą strategię użyć, zależy od platformy db. W MySql domyślnie będzie to IDENTITY, a pole będzie wtedy auto_increment.

Można zapisać adnotację id bez nawiasów w następujący sposób.

  • ORM \ Id
 1
Author: Bram Gerritsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-23 10:57:27

Podczas gdy ja seconding UUID podejście sugerowane przez Jonhathan, można wolą krótszy, bardziej czytelny, identyfikator. W tym przypadku możesz użyć ShortId Doctrine bundle .

 1
Author: Massimiliano Arione,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-07 13:06:57