I want to generate a unique ticket ID for my tickets. But how to let doctrine generate a unique id?
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
little more explain:
- id must be 6 charters like: 678915
- id must be unique
As of version 2.3, you can just add the following annotations to your property:
While I'm seconding the UUID approach suggested by Jonhathan, you could prefer a shorter, more readable, identifier. In this case you can use ShortId Doctrine bundle.
You can use the PrePersist annotation, like this:
As the annotation name suggest, it will be run before object persistence into database.
For unique id, I simply use a native php uniqid() function http://php.net/manual/en/function.uniqid.php which will return 13 characters. To get only 6 characters, refer to this PHP Ticket ID Generation
In the $id property, I think you also need to remove this line to prevent auto generated value of it:
Doctrine will treat this field as your primary key (because of the
@Id
annotation), so this field is already unique. If you have the@GeneratedValue
annotation onAUTO
strategy Doctrine will figure out which strategy to use dependend on the db platform. It will default toIDENTITY
on MySql and the field will be aauto_increment
then.You can write the id annotation without the brackets as follows.
Use custom GeneratedValue strategy:
1. In your Entity class:
2. Then create file
AppBundle/Doctrine/RandomIdGenerator.php
with content