Doctrine 2 provides the ability to set default values for entity properties. This is particularly useful when you want to initialize properties with specific values during entity creation.
To set a default value using the array syntax, specify the default key within the options array of the @ORMColumn annotation. For instance:
<code class="php">#[ORM\Entity] class myEntity { #[ORM\Column(options: ["default" => 0])] private int $myColumn; // ... }</code>
Here, myColumn will be initialized with the value 0 whenever a new myEntity object is created.
Alternatively, you can use the annotation syntax to specify the default value:
<code class="php">/** * @Entity */ class myEntity { /** * @var string * * @ORM\Column(name="myColumn", type="integer", options={"default" : 0}) */ private $myColumn; ... }</code>
Both methods achieve the same result. It's worth noting that this approach uses SQL DEFAULT, which may not be supported for certain data types like BLOB and TEXT.
The above is the detailed content of How to Set Default Values for Entity Properties in Doctrine 2?. For more information, please follow other related articles on the PHP Chinese website!