简体   繁体   English

Symfony2:Sonata实体中的自定义标识符

[英]Symfony2: Custom identifier in Sonata entities

I have an entity with a custom id (ie UUID) generated on __construct function. 我有一个在__construct函数上生成的具有自定义ID(即UUID)的实体。

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. 我需要在持久化和刷新之前将此实体具有ID,所以我不能使用自动增量。

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. 因此,问题在于奏鸣曲不允许我创建实体,因为它使用create选项作为执行工具并在执行时进行编辑,因为该实体已经具有ID,但是此实体目前不存在,因此失败。

The problem isn't the library for generating UUID, any value for 'id' fails. 问题不是生成UUID的库,'id'的任何值都会失败。

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. 您不应该在构造函数中设置id,而应使用prePersist主义事件在第一次持久存储之前更改您的实体。

You may use annotations to do so, see the Doctrine Documentation on prePersist . 您可以使用注释来这样做,请参阅prePersist上的《 Doctrine文档》

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. 在构造函数中设置id的问题在于,当您从数据库中检索ID时,您可以覆盖它,在这种情况下,它将是不正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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