How to set a date in Doctrine 2?

前端 未结 2 704
旧时难觅i
旧时难觅i 2021-01-07 16:56

I have a field named \"birthday\" in doctrine entity.

I would like to create an object to add to database using doctrine.

Inside the controller :

<         


        
2条回答
  •  -上瘾入骨i
    2021-01-07 17:32

    Fields of your entities mapped as "datetime" or "date" should contain instances of DateTime.

    Therefore, your setter should be type-hinted as following:

    /**
     * Set birthday
     *
     * @param \DateTime|null $birthday
     */
    public function setBirthday(\DateTime $birthday = null)
    {
        $this->birthday = $birthday ? clone $birthday : null;
    }
    
    /**
     * Get birthday
     *
     * @return \DateTime|null 
     */
    public function getBirthday()
    {
        return $this->birthday ? clone $this->birthday : null;
    }
    

    This allows setting either null or an instance of DateTime for the birthday.

    As you notice, I also clone the values for the birthday date to avoid breaking encapsulation (see Doctrine2 ORM does not save changes to a DateTime field ).

    To set the birthday, you then simply do following:

    $student->setBirthday(new \DateTime('11-11-90'));
    

提交回复
热议问题