Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine default value vs null insert

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

I'm using Symfony3 and Doctrine2 and MariaDB.

Let's assume that I've created something like this in my entity:

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

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

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

But what's the point of having this when every time I try to save data into database(I'm trying 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 rest of the fields on the object are null.

I can work around this by setting the default values in the constructor or by allowing for null values in the DB.

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

So what I would like to know:

  • are setting default value in entity or allowing nulls in DB only ways to do this?
  • is there something wrong with my logic here?
  • is there any cooler and cleaner way of doing this?
like image 736
Robert Avatar asked Apr 03 '17 23:04

Robert


1 Answers

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

/**
 * @ORM\Column(
 *     name="status",
 *     type="boolean",
 *     options={"default": 0}
 * )
 */
private $status = 0;
like image 57
Mawcel Avatar answered Oct 23 '22 16:10

Mawcel