I'm trying to avoid entering 0 or 1 for $locked
field manually so I assigned default as 0 in @ORM
annotations however it doesn't work as expected so I'm getting error below. I though options={"default"=0}
would handle it but appears as it does not handle it!
Is there a way of assigning 0 by defauls so that the INSERT statement doesn't fail?
Note: I can sort it out with a prePersist()
method, __construct()
or $locked = 0;
so on but what I'm interested in is @ORM annotation solution.
If @ORM annotation doesn't handle it what is the point of having options={"default"=0}
since it markes fields default value in database? See image below.
Error:
DBALException: An exception occurred while executing "INSERT INTO user (username, locked) VALUES (?, ?)" with params ["username", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column "locked" cannot be null
User Entity:
/**
* @var boolean
* @ORM\column(type="boolean", options={"default"=0})
*/
protected $locked;
Controller:
$user: new USer();
$user->setUsername('username');
$em->persist($user);
$em->flush();
Inserting a default value can be done in various ways such as Default entity property value using constructor or setter. Other ways like using JPA with columnDefinition have the drawback that they insert a null by default and the default value of the DBMS does not precede.
Default column values in JPA. JPA allows to generate Schema definitions when you set hibernate. hbm2ddl. auto value to create or create-drop or update .
This is all you need:
/**
* @var boolean
* @ORM\column(type="boolean")
*/
protected $locked = 0;
or:
/**
* @var boolean
* @ORM\column(type="boolean")
*/
protected $locked = false;
UPDATE
Doctrine does not support to set the default values in columns through the “DEFAULT” keyword in SQL.
http://docs.doctrine-project.org/en/latest/reference/faq.html#how-can-i-add-default-values-to-a-column
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With