如何设置原则2日期?(How to set a date in Doctrine 2?)

2019-07-29 16:36发布

我有一个在教义实体名为“生日”字段。

我想创建一个对象使用学说添加到数据库中。

内部控制器:

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

Answer 1:

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


Answer 2:

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

这允许设置或者null或实例DateTime的生日。

正如你看到的,我也clone的生日日期,以避免破坏封装的值(见Doctrine2 ORM不更改保存到DateTime字段 )。

要设置的生日,你再简单地做以下:

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


文章来源: How to set a date in Doctrine 2?