需要在实体的constructor中生成UUID值,并将其设为主键,例如:
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
/**
* @ORM\Entity(repositoryClass="App\Repository\MyEntityRepository")
*/
class MyEntity
{
/**
* @ORM\Id()
* @ORM\Column(type="string", length=36, unique=true)
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
public function __construct()
{
$this->id = Uuid::uuid4();
}
public function getId(): ?string
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
}
在此示例中,我们使用了Ramsey\Uuid库来生成UUID。我们在实体的构造函数中使用了uuid4()方法生成一个新的UUID,并将其设置为实体的$id属性,该属性在主键注释中定义。这将确保在save()方法中执行插入时,ID将始终是一个有效值。