Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default value to a field with ORM annotations and handling queries

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.

enter image description here

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();
like image 598
BentCoder Avatar asked Oct 07 '14 15:10

BentCoder


People also ask

How do I set the default value in an entity field?

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.

What is the default value in hibernate?

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 .


1 Answers

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

like image 65
dmnptr Avatar answered Oct 20 '22 17:10

dmnptr