简体   繁体   中英

How to get all possible values for an existing ENUM or SET - field

I'm using Doctrine in Symfony4.
How do I retrieve all possible values for an ENUM or SET column on this base?

我有同样的gettin枚举值问题,只需将数据库从枚举更改为int

First of all, I suggest you add a abstraction layer instead extend directly Enum even if is not necessary.

class AppEnum extends Enum
{
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    protected $value;

Then you just need to add static function on it.

public static function choices()
{
    $values = [];

    foreach (static::toArray() as  $value) {
        $values[] = new static($value);
    }

    return $values;
}

Example: Assume you have an enum.

class ExampleEnum extends AppEnum
{
    public const A = '1';
    public const B = '2';
    public const C = '3';

And then:

dump(ExampleEnum::choices());

will return:

    array:3 [
  0 => App\Gateway\Domain\Darva\CalculationElement {#15121
    #value: "1"
    -key: "A"
  }
  1 => App\Gateway\Domain\Darva\CalculationElement {#15065
    #value: "2"
    -key: "B"
  }
  2 => App\Gateway\Domain\Darva\CalculationElement {#15124
    #value: "3"
    -key: "C"
  }
]

Old post but hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM