如何在Doctrine 2中设置日期?

时间:2012-05-31 14:59:10

标签: symfony doctrine doctrine-orm

我在教条实体中有一个名为“birthday”的字段。

我想创建一个使用doctrine添加到数据库的对象。

控制器内部:

$name = "John Alex";
$birthday = "11-11-90";
$student = new Student();
$student->setName($name);
$student->setBirthday(strtotime($birthday);
...

但是当我试图坚持时,我得到了这个错误

Fatal error: Call to a member function format() on a non-object in /Library/WebServer/Documents/Symfony/vendor/doctrine-dbal/lib/Doctrine/DBAL/Types/DateType.php on line 44

修改

我的实体:

/**
 * @var string $name
 *
 * @ORM\Column(name="name", type="string", length=255)
 */
private $name;

/**
 * @var date $birthday
 *
 * @ORM\Column(name="birthday", type="date", nullable=true)
 */
private $birthday;

/**
 * Set birthday
 *
 * @param date $birthday
 */
public function setBirthday($birthday)
{
    $this->birthday = $birthday;
}

/**
 * Get birthday
 *
 * @return date 
 */
public function getBirthday()
{
    return $this->birthday;
}

2 个答案:

答案 0 :(得分:39)

$name = "John Alex";
$birthday = "11-11-1990"; // I changed this
$student = new Student();
$student->setName($name);
$student->setBirthday(new \DateTime($birthday)); // setting a new date instance
// ...

答案 1 :(得分:27)

映射为"datetime""date"的实体字段应包含DateTime的实例。

因此,您的setter应按类型提示如下:

/**
 * 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;
}

这允许为生日设置nullDateTime的实例。

正如您所注意到的那样,我还clone生日日期的值,以避免破坏封装(请参阅Doctrine2 ORM does not save changes to a DateTime field)。

要设置生日,您只需执行以下操作:

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