【问题标题】:Generating UUIDs is not working with Symfony 5.3生成 UUID 不适用于 Symfony 5.3
【发布时间】:2022-11-11 21:37:18
【问题描述】:

我想为 RFC 4122 格式的新实体生成 ID(例如 c9bb9b5a-2950-4f02-a9df-3925a0b62513)

https://symfony.com/doc/5.3/components/uid.html#generating-ulids https://symfony.com/bundles/DoctrineBundle/current/custom-id-generators.html

我首先用我自己的 IdGenerator 类进行了尝试:

<?php

namespace App\Service;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AbstractIdGenerator;
use Symfony\Component\Uid\Uuid;

class IdGenerator extends AbstractIdGenerator
{
    public function generate(EntityManager $em, $entity)
    {
        $uuid = Uuid::v4();
        return $uuid;
    }
}

实体:

/**
 * @ORM\Id
 * @ORM\Column(type="uuid", unique=true)
 * @ORM\GeneratedValue(strategy="CUSTOM")
 * @ORM\CustomIdGenerator(class="App\Service\IdGenerator")
 */
private $id;

我用 XDebug 调试了它。它进入了正确的类和函数,创建并返回了正确的 UUID,但是当我尝试加载我的固定装置时仍然遇到相同的错误:

 An exception occurred while executing 'INSERT INTO step (id, text, periodically, necessary, activated, created_at, modified_at, created_b  
  y, modified_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["\x2b\x06\x41\x56\x73\xb0\x4f\xd2\x80\xfa\xa2\x87\xd1\xed\x31\x5f", "ste  
  p1", 0, 0, 1, "2022-02-12 23:35:58", "2022-02-12 23:35:58", "housemeister-system", "housemeister-system"]:                                 
                                                                                                                                             
  SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xB0O\xD2\x80\xFA\xA2...' for column 'id' at row 1     

不知何故,它仍然试图将其作为二进制插入。

我的第二次尝试是在实体的构造函数中手动生成它:

public function __construct()
{
    $uuid = Uuid::v4()->__toString();
    $this->id = $uuid;
}

同样的结果,同样的错误信息。有人有想法吗?

编辑: 最近在我的 Symfony 5.3 项目中更新了学说。似乎此更新将 id 类型从 char(36) 更改为 binary(16)。也许上下文信息会有所帮助。

【问题讨论】:

  • 您是否在数据库中手动创建了该字段? Uuid 不是真正的字符串,它们是 128 位数字。 MySQL 直到最近才添加原生类型,所以之前它是一个 16 字节的二进制字段;教义仍然使用它来实现兼容性。尝试删除该字段并使用迁移或bin/console doctrine:schema:update 创建它。
  • 好的,do:mi:di 显示它想将我的 id 从 char(36) 更改为 binary(16)。我想以某种方式防止这种情况,因为 prod DB 上的所有数据都使用 char36 uuid。我最近在我的 symfony 项目中更新了学说,所以这一定以某种方式触发了它。
  • 正如我所说,为了兼容性,MySQL/MariaDB 上的uuid 被映射为 BINARY(16),并且一直如此。如果您不喜欢使用字符串,那么不要声明type="uuid",而是声明type="text", length=36。不过我不推荐它:该字段的数据和索引会更大,唯一检查会更昂贵,这取决于您可能需要调整内存等的数据库大小。或者您可能希望实现自己的类型以采用注意从字符串到Uuid 的转换。

标签: php symfony doctrine uuid


【解决方案1】:

我有同样的问题,我用以下方法修复它:

composer require ramsey/uuid-doctrine

【讨论】:

    猜你喜欢
    • 2012-08-30
    • 1970-01-01
    • 2012-07-15
    • 2014-09-16
    • 1970-01-01
    • 2017-02-11
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多