K
K
Kripto772019-09-27 12:42:05
symfony
Kripto77, 2019-09-27 12:42:05

How to give NULL instead of default_value in Symfony 4.3 entity (datetime field type)?

MySQL/MariaDB base, datetime field with default value = "0000-00-00 00:00:00". According to the recommendations, NULL is not set, because with default_value, the speed of sampling from the database is faster.

//src/Entity/Customer.php

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="last_bill_date", type="datetime", nullable=false, options={"default"="0000-00-00 00:00:00"})
     */
    private $lastBillDate;

    /**
     * @return \DateTime
     */
    public function getLastBillDate(): \DateTime
    {
        return $this->lastBillDate;
    }

In the default_value case, it returns a DateTime('0000-00-00 00:00:00') object, given the time zone.
Further, problems naturally arise, for example, in Twig a date like -0001-11-30 00:00:00 with type="datetime" in getLastBillDate(), a ready-made DateTime comes:
//src/Entity/Customer.php

    /**
     * @ORM\Column(name="last_bill_date", type="string")
     */
    private $lastBillDate;

    /**
     * @return null|\DateTime
     */
    public function getLastBillDate(): ?\DateTime
    {
        $result = $this->lastBillDate !== '0000-00-00 00:00:00' ? new \DateTime($this->lastBillDate) : NULL;

        return $result;
    }

Tell me how to do it right

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question