Answer the question
In order to leave comments, you need to log in
How to configure the accepted values of some fields in an entity?
An example in essence is the type field, it can take one of the following values: sell, buy, rent, rent.
How to replace them with the corresponding keys without creating a separate table for a few types.
And at request to receive specific value, instead of a key.
Do I need to use a config file for this?
Answer the question
In order to leave comments, you need to log in
You can use the enum data type in a record. Enum is designed for this. The database will use a number, and when getting data from the database, there will be a string.
Here is the standard solution in the doctrine dock .
If there is only one enum, then you can do so. But often there are a lot of enums, and then I do this way:
Base class:
<?php
namespace AppBundle\DBAL;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
abstract class EnumType extends Type
{
protected $name;
public static $VALUES = array();
public static function getValues()
{
$values = array();
foreach (static::$VALUES as $value) $values[$value] = $value;
return $values;
}
public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
$values = array();
foreach (static::$VALUES as $value) $values[] = "'$value'";
return "ENUM(".implode(", ", $values).") COMMENT '(DC2Type:$this->name)'";
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return $value;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (!in_array($value, static::$VALUES)) {
throw new \InvalidArgumentException("Invalid value '$value' for enum '$this->name'.");
}
return $value;
}
public function getName()
{
return $this->name;
}
}
<?php
namespace AppBundle\DBAL;
class MyType extends EnumType
{
protected $name = 'mytype';
const FIRST = 'first';
const SECOND = 'second';
public static $VALUES = array(self::FIRST, self::SECOND);
}
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
types:
mytype: AppBundle\DBAL\MyType
mapping_types:
enum: string
class MyEntity
{
/**
* @var integer $id
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// ....
/**
* @var string
*
* @ORM\Column(type="mytype")
*/
protected $type;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question