Reputation: 12720
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();
Upvotes: 13
Views: 23750
Reputation: 1068
With Doctrine ORM v3 you can do it using the options
property at the Column
attribute:
#[Column(
type: "integer",
nullable: false,
options: ["default" => 0]
)]
protected $loginCount;
But Doctrine seems not to encourage this as they negate the possibility here: https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/faq.html#how-can-i-add-default-values-to-a-column
Upvotes: 2
Reputation: 4304
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.
Upvotes: 26