heymoon / doctrine-psql-enum
将 PHP8.1 原生枚举存储为 PostgreSQL 自定义枚举类型
1.0.0
2023-09-24 14:47 UTC
Requires
- php: >=8.1
- doctrine/doctrine-bundle: 2.*
- doctrine/orm: 2.*
- symfony/framework-bundle: 6.*
Requires (Dev)
- doctrine/doctrine-migrations-bundle: 3.*
- phpunit/phpunit: ^9.5
- symfony/orm-pack: 2.*
- symfony/yaml: 6.*
README
先决条件: Symfony 6 + Doctrine 2
安装
composer require heymoon/doctrine-psql-enum
用法
创建库配置
config/packages/doctrine_postgres_enum.yaml
doctrine_postgres_enum: type_name: enum migrations: enabled: true comment_tag: DC2Enum
要定义新的枚举类型,请使用原生 PHP 枚举
enum AuthStatus: string { case New = 'new'; case Active = 'active'; case Inactive = 'inactive'; case Deleted = 'deleted'; } enum Service: string { case Google = 'google'; }
在模型中创建枚举字段时,使用 enum
作为 type
值,必须在 Column
属性中定义 enumType
#[ORM\Entity(repositoryClass: AuthRepository::class)] class Auth { #[ORM\Id] #[ORM\GeneratedValue(strategy: "CUSTOM")] #[ORM\CustomIdGenerator(class: "doctrine.uuid_generator")] #[ORM\Column(type: 'uuid')] private Uuid $id; #[ORM\Column(type: 'enum', enumType: AuthStatus::class)] private AuthStatus $status; #[ORM\Column(type: 'enum', enumType: Service::class)] private Service $service; }
通过 make:migration
创建迁移。如果枚举已创建或修改,迁移中会添加 CREATE TYPE
/ALTER TYPE
调用。示例
$this->addSql('DROP TYPE IF EXISTS app_entity_type_authstatus'); $this->addSql('CREATE TYPE app_entity_type_authstatus AS ENUM (\'new\',\'active\',\'inactive\',\'deleted\')'); $this->addSql('DROP TYPE IF EXISTS app_entity_type_service'); $this->addSql('CREATE TYPE app_entity_type_service AS ENUM (\'google\')'); $this->addSql('CREATE TABLE auth (id UUID NOT NULL, status app_entity_type_authstatus NOT NULL, service app_entity_type_service NOT NULL, PRIMARY KEY(id))'); $this->addSql('COMMENT ON COLUMN auth.status IS \'(DC2Enum:App\\Entity\\Type\\AuthStatus)\''); $this->addSql('COMMENT ON COLUMN auth.service IS \'(DC2Enum:App\\Entity\\Type\\Service)\'');