在 Symfony 的 Sonata Admin Bundle 中使用 Doctrine Uuid 类型

Using Doctrine Uuid type with Sonata Admin Bundle for Symfony

我在使 Sonata Admin Bundle 使用 Ramsey 的 Uuid 作为实体 ID 时遇到问题。

这是我在尝试显示国家/地区列表时遇到的错误 (/admins/app/country/list)

An exception has been thrown during the rendering of a template ("Unknown database type uuid requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.").

doctrine.yaml

doctrine:
    dbal:
        types:
            uuid: Ramsey\Uuid\Doctrine\UuidType

services.yaml

sonata.admin.country:
    class: App\Admin\CountryAdmin
    arguments: [~, App\Entity\Country, ~]
    tags:
        - { name: sonata.admin, manager_type: orm, group: Entities, label: Country }

App\Entity\Country

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

App\Admin\Country

final class CountryAdmin extends Sonata\AdminBundle\Admin\AbstractAdmin
{    
    protected function configureRoutes(RouteCollection $collection)
    {
        $collection
            ->add('show_country', sprintf('%s/show_country', $this->getRouterIdParameter()));
    }
}

App\Controller\Admin\CountryController

class CountryController extends Sonata\AdminBundle\Controller\CRUDController
{
    public function showCityAction(Request $request): Response
    {
        /** @var Country $country */
        $country = $this->admin->getSubject();

        if (!$country) {
            $id = $request->get($this->admin->getIdParameter());
            throw $this->createNotFoundException(sprintf(
                'Unable to find the object with id : %s',
                $id
            ));
        }

        return $this->renderWithExtraParams('admin/city/show_country.html.twig', [
            'show_country' => $country,
        ]);
    }
}

composer.json

    "sonata-project/admin-bundle": "^3.53",
    "sonata-project/doctrine-orm-admin-bundle": "^3.10",
    "sonata-project/translation-bundle": "^2.4",
    "sonata-project/user-bundle": "^4.4",
    "stof/doctrine-extensions-bundle": "^1.3",
    "sonata-project/easy-extends-bundle": "^2.5",
    "ramsey/uuid-doctrine": "^1.5"

似乎未加载 Uuid 类型,尽管它在 doctrine.yaml 配置文件中。我试图将它手动包含在 bootstrap.php:

\Doctrine\DBAL\Types\Type::addType('uuid', 'Ramsey\Uuid\Doctrine\UuidType');

但我只是收到一条错误消息,指出该类型已包含在内。

我意识到 vendor/sonata-project/doctrine-extensions/src/Types 只包含 JsonType.php。难道是 Uuid.php 不见了?还是我错过了其他东西?感谢您的帮助!

我终于找到了这个问题的答案。我所要做的就是将 2 行添加到 doctrine.yaml 文件中:

doctrine:
    dbal:
        types:
            uuid: Ramsey\Uuid\Doctrine\UuidType
        mapping_types:   <---
            uuid: uuid   <---

我希望它能对某人有所帮助,因为我个人无法在互联网上的任何地方找到这些信息!