当我在Symfony中使用columnDefinition来定义一个ENUM列时,我需要将可能的值写成pain文本:
columnDefinition="ENUM('red', 'blue', 'green')"因为这可能会在以后的阶段导致错误,所以我希望能够在其中放置一个数组:
columnDefinition="ENUM(static::COLORS)"我该如何解决这个问题呢?
发布于 2021-01-23 23:52:34
您可以将枚举创建为类型并使用它
<?php
namespace App\DBAL;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class EnumColorsType extends Type
{
const ENUM_COLORS = 'enum_colors';
const COLOR_RED = 'red';
const COLOR_BLUE = 'blue';
const COLOR_GREEN= 'green';
publkic static $AVAILBLE_COLORS = ['blue','red','green'];
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return sprintf("ENUM(%s)",implode(',', static::$AVAILBLE_COLORS));
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return $value;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (!in_array($value, static::$AVAILBLE_COLORS)) {
throw new \InvalidArgumentException("Invalid Colors");
}
return $value;
}
public function getName()
{
return self::ENUM_COLORS;
}
public function requiresSQLCommentHint(AbstractPlatform $platform)
{
return true;
}
}然后使用它
<?php
...
/**
* @ORM\Entity
*/
class YourEntity
{
/**
* @Column(type="enum_colors")
*/
private $color;
}https://stackoverflow.com/questions/65829909
复制相似问题