The default value for Doctrine vs null

There is something that bothers me. I tried to find one clear answer, but so far no luck.

I use Symfony3 and Doctrine2 and MariaDB.

Suppose I created something like this in my essence:

/** * @ORM\Column( * name="status", * type="boolean", * options={"default": 0} * ) */ private $status; 

Now thanks to this, I have a field with a default value of 0 in the database:

 `status` tinyint(1) NOT NULL DEFAULT '0', 

But what is the point of having this when every time I try to save data in a database (I try to save only, for example, 1 out of 10 fields):

 $story->setContent('Test Content'); $em = $this->getDoctrine()->getManager(); $em->persist($story); $em->flush(); 

I get:

 SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'status' cannot be null 

Because, of course, the remaining fields on the object are zero.

I can get around this by setting default values ​​in the constructor or by allowing zero values ​​in the database.

What if I do not want to do this? Is there any other way that I am missing here?

So what I would like to know:

  • Do they set the default value in entities or only allow NULL in DB?
  • Is there something wrong with my logic here?
  • is there a cooler and cleaner way to do this?
+5
source share
1 answer

Like the @Cerad comment, you just need to initialize the property in your actual entity class

 /** * @ORM\Column( * name="status", * type="boolean", * options={"default": 0} * ) */ private $status = 0; 
+4
source

Source: https://habr.com/ru/post/1266277/


All Articles