Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine not creating auto UUID

I'm having a trouble. When I perform an persist() and flush() in Symfony, I'm getting this:

An exception occurred while executing 'INSERT INTO pedido (emissao, total, cliente_id) VALUES (?, ?, ?, ?)' with params ["2018-01-10", "100.00", "65c4002a-06e2-442b-b1da-61197f73ba3b"]: SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value

My annotation is the same in all entities, but in this one (specifically), Doctrine can not create auto id:

/**
 * @var \Ramsey\Uuid\Uuid
 *
 * @ORM\Id
 * @ORM\Column(type="uuid", unique=true)
 * @ORM\GeneratedValue(strategy="CUSTOM")
 * @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")
 */
protected $id;

As the field ID is generated automatically, this error appears to make no sense. I have others entities like Pessoa which works fine with the same annotation.

How can I force Doctrine to "understand" the UUID index?

like image 482
Luiz Gonçalves Avatar asked Dec 08 '22 16:12

Luiz Gonçalves


1 Answers

Currenly Doctrine does not support more than one autogenerated field in single entity. If there are 2 fields Doctrine will generate value for the last one and left first field with default value (null if not specified).

Since Ramsey uses static methods to generate UUID you should place it's generation where persistent logic is (manager, handler or whatever) or inside entity's constructor:

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

And remove corresponding annotations:

* @ORM\GeneratedValue(strategy="CUSTOM")
* @ORM\CustomIdGenerator(class="Ramsey\Uuid\Doctrine\UuidGenerator")

Another solution

Since your second column uses auto increment feature of database (I assume you are using MySQL) you can try to:

  1. Remove generator annotations on this column
  2. Define column definition (non-portable and hacky IMHO) manually with AUTO_INCREMENT option:
    1. http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#column
    2. https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html
like image 92
Vadim Ashikhman Avatar answered Dec 10 '22 21:12

Vadim Ashikhman