如何在Doctrine 2中设置日期?

Moh*_*med 27 doctrine symfony doctrine-orm

我在教义实体中有一个名为"birthday"的字段.

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

控制器内部:

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

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

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
Run Code Online (Sandbox Code Playgroud)

编辑:

我的实体:

/**
 * @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;
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*med 40

$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
// ...
Run Code Online (Sandbox Code Playgroud)


Ocr*_*ius 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;
}
Run Code Online (Sandbox Code Playgroud)

这允许设置生日的任一个null或实例DateTime.

正如您所注意到的,我也是clone生日日期的值,以避免破坏封装(请参阅Doctrine2 ORM不保存对DateTime字段的更改).

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

$student->setBirthday(new \DateTime('11-11-90'));
Run Code Online (Sandbox Code Playgroud)