Symfony/Doctrine: DateTime as primary key

前端 未结 3 626
南笙
南笙 2020-12-19 10:38

I am trying to make an Entity using a date as a primary key. The problem is that Symfony can\'t convert the DateTime I\'m using into a string to introduce it in the Identity

3条回答
  •  天命终不由人
    2020-12-19 11:22

    I had the same problem here. I worked around it by using this:

    /**
     * @var string
     *
     * @ORM\Id
     * @ORM\Column(type="string")
     */
    private $date;
    
    /**
     * @return \DateTime
     */
    public function getDate()
    {
        return \DateTime::createFromFormat('Y-m-d|', $this->date);
    }
    
    /**
     * @param \DateTime $date
     */
    public function __construct(\DateTime $date)
    {
        $this->date = $date->format('Y-m-d');
    }
    

    if you want to use datetime, you should use a different format like \DateTime::ISO8601. Be careful at saving stuff with timezones.

提交回复
热议问题