Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value in Doctrine

How do I set a default value in Doctrine 2?

like image 972
Jiew Meng Avatar asked Jul 31 '10 04:07

Jiew Meng


People also ask

How do you define a default value?

A default value is the value that is inserted into a column when an explicit value is not specified in an INSERT statement. A default value can be a literal character string that you define or one of the following SQL constant expressions: USER.

What is a default value example?

A DEFAULT value clause in a data type specification explicitly indicates a default value for a column. Examples: CREATE TABLE t1 ( i INT DEFAULT -1, c VARCHAR(10) DEFAULT '', price DOUBLE(16,2) DEFAULT 0.00 ); SERIAL DEFAULT VALUE is a special case.

What is default null value?

If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.

Why are default values used?

Default values are very often used as an aid to data entry. If we can provide data to users that is most often the data that they would have entered, then we would have done them a favor and sped up data entry.


2 Answers

<?php /**  * @Entity  */ class myEntity {     /**      * @var string      *      * @ORM\Column(name="myColumn", type="integer", options={"default" : 0})      */     private $myColumn;     ... } 

Note that this uses SQL DEFAULT, which is not supported for some fields like BLOB and TEXT.

like image 147
iv3ndy Avatar answered Sep 23 '22 22:09

iv3ndy


Database default values are not "portably" supported. The only way to use database default values is through the columnDefinition mapping attribute where you specify the SQL snippet (DEFAULT cause inclusive) for the column the field is mapped to.

You can use:

<?php /**  * @Entity  */ class myEntity {     /**      * @var string      *      * @Column(name="myColumn", type="string", length="50")      */     private $myColumn = 'myDefaultValue';     ... } 

PHP-level default values are preferred as these are also properly available on newly created and persisted objects (Doctrine will not go back to the database after persisting a new object to get the default values).

like image 44
romanb Avatar answered Sep 25 '22 22:09

romanb