如何在Doctrine 2中设置日期?

27

我在Doctrine实体中有一个名为“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;
}

你能展示一下与学生相关的实体吗?你有查看过这个答案吗:http://stackoverflow.com/questions/7463137/saving-a-zend-date-in-the-database-with-doctrine-2-1? - j0k
请在此处查看翻译的内容:http://paste.ubuntu.com/p/GMXrJfKfBZ/ - AKRAM EL HAMDAOUI
你有查看过这个答案吗?- 关于 DateTime。 - j0k
2个回答

41
$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
// ...

太棒了,那正是我的问题,我试图在MySQL数据库中手动设置一些日期时间类型。 - blamb

30

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

因此,您的设置器应按以下方式进行类型提示:

/**
 * 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 实例。

正如您所注意到的,我还针对生日日期进行了克隆以避免破坏封装性(请参见Doctrine2 ORM 不保存 DateTime 字段的更改)。

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

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

php app/console doctrine:generate:entities只生成了以下方法头* @param \DateTime $birthdate, * @return Person, public function setBirthdate($birthdate)。 当我采用这个方法头 public function setBirthdate(\DateTime $birthdate = NULL)时,我得到了 Argument 1 passed to<...>::setBirthdate() must be an instance of DateTime, string given 。但字符串为空(因为表单字段未填充)。 - rabudde
@rabudde,你不应该生成实体。实体是你的代码库的一部分,也是你领域的核心组件。生成的代码通常是一个坏主意,因为在生成后你避免测试它。此外,看起来你的表单没有将空值转换为“null”值。 - Ocramius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接