我在教义实体中有一个名为“生日”的领域。
我想要创建一个对象,以添加到数据库使用的理论。
在控制器内部:
$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;
}发布于 2012-05-31 16:16:30
$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
// ...发布于 2013-03-20 09:07:13
映射为"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 does not save changes to a DateTime field )。
要设置生日,只需执行以下操作:
$student->setBirthday(new \DateTime('11-11-90'));https://stackoverflow.com/questions/10836123
复制相似问题