27

我在学说实体中有一个名为“生日”的字段。

我想创建一个对象以使用教义添加到数据库中。

控制器内部:

$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;
}
4

2 回答 2

42
$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
// ...
于 2012-05-31T16:16:30.493 回答
30

您的实体的字段映射为"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;
}

这允许为生日设置一个null或一个实例。DateTime

如您所见,我还clone设置了生日日期的值以避免破坏封装(请参阅Doctrine2 ORM 不会保存对 DateTime 字段的更改)。

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

$student->setBirthday(new \DateTime('11-11-90'));
于 2013-03-20T09:07:13.307 回答