简体   繁体   中英

Symfony2: Custom identifier in Sonata entities

I have an entity with a custom id (ie UUID) generated on __construct function.

namespace AppBundle\Entity;
use Rhumsaa\Uuid\Uuid;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
*/
class Person
{
    /**
    * @ORM\Id
    * @ORM\Column(type="string")
    */
    private $id;

    /**
    * @ORM\Column(type="string")
    */
    private $name;

    public function __construct()
    {
        $this->id = Uuid::uuid4()->toString();
    }

This entity is used in sonata and also in other part of the project. I need this entity to have id before persisting and flushing it, so I can not use a an auto-increment.

So, the problem is sonata don't let me create entities because it takes the create option as and edit on executing because that entity already has an id, but this entity does not exists at this moment, so it fails.

The problem isn't the library for generating UUID, any value for 'id' fails.

Anyone know how to solve it? Another similar approach to solve the problem?

You shouldn't set your id in the constructor, but rather use the prePersist Doctrine event to alter your entity before persisting it for the first time.

You may use annotations to do so, see the Doctrine Documentation on prePersist .

The issue with setting the id in the constructor is that you may override it when you're retrieving it from the database, in which case it will be incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM