zelazowy
zelazowy

Reputation: 1056

How to use char instead of varchar when generating db tables from entities?

I'm using string(32) instead of integer for entity id field (it simulates guid type). But after creating database table from entity ids field type is set to varchar(32). I think it's not the best idea, guid always has length = 32 so char type will be more appropriate.

Is there a way to tell Doctrine to use char or the only way is to change it manually in database?

Upvotes: 21

Views: 6826

Answers (2)

Francesco Casula
Francesco Casula

Reputation: 27130

Although the althaus solution works fine I think this one should be the canonical way of doing it:

With annotations:

/**
 * @Column(type="string", length=2, options={"fixed" = true})
 */
protected $country;

With YAML (example of both ID and non-ID field):

Your\Nice\Entity:
    id:
        id:
            type: string
            length: 32
            options:
                fixed: true
    fields:
        country:
            type: string
            length: 2
            options:
                fixed: true
  • options: Array of additional options:
    • fixed: Boolean value to determine if the specified length of a string column should be fixed or varying (applies only for string/binary column and might not be supported by all vendors).

Official documentation

Upvotes: 37

althaus
althaus

Reputation: 2017

You can tell Doctrine to use vendor specific field types:

/**
 * @Column(type="string", columnDefinition="CHAR(2) NOT NULL")
 */
protected $country;

Source

Upvotes: 7

Related Questions