How can I map a single char column in Doctrine 2, using annotations? I would like to have a char type, instead a single char string.
Asked
Active
Viewed 1.1k times
3 Answers
55
You can always use the string type with the fixed option:
/**
* @Column(type="string", length=2, options={"fixed" = true})
*/
protected $country;
The above code snippet produces the following SQL:
`country` char(2) NOT NULL,

Eddie C.
- 918
- 10
- 16

Francesco Casula
- 26,184
- 15
- 132
- 131
-
3I would like to add this note for PostgreSQL, from the [docs](http://www.postgresql.org/docs/9.3/static/datatype-character.html): There is no performance difference among char, varchar and text, apart from increased storage space when using the char(n), and a few extra CPU cycles to check the length when storing into a length-constrained column. While char(n) has performance advantages in some other databases, there is no such advantage in PostgreSQL; in fact char(n) is usually the slowest, because of its additional storage costs. In most situations text or varchar should be used instead. – edigu Mar 18 '15 at 20:14
2
Doctrine doesn't have a CHAR type defined out of the box, however it does allow you to define custom types, which you could use to create a 'char' type to use in annotations.
The Doctrine documentation has an example of this: http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#custom-mapping-types

Kevin Sharp
- 521
- 4
- 6
2
You might end up providing your own full-column definition:
/**
* @Column(type="string", columnDefinition="CHAR(2) NOT NULL")
*/
protected $country = null;

Eddie C.
- 918
- 10
- 16

Антон Кучеревский
- 49
- 2
-
2You usually don't want to use the columnDefinition property since most likely you are tying yourself to one database engine – Dennis Haarbrink Nov 17 '16 at 07:47