簡體   English   中英

Symfony + Doctrine 2.2 DateTime列錯誤

[英]Symfony + Doctrine 2.2 DateTime column error

我很難解決這個問題。 嘗試保留實體時出現以下錯誤(請參見下面的源代碼):

Fatal error: Call to a member function format() on a non-object 
in *****\vendor\doctrine-dbal\lib\Doctrine\DBAL\Types\DateTimeTzType.php 
on line 64

這是實體代碼的片段:

namespace ****\Bundle\****Bundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;

use Doctrine\ORM\Mapping as ORM;

use Symfony\Component\Validator\Constraints as Assert;

/**
 * ****\Bundle\****Bundle\Entity\MyEntity
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="****\Bundle\****Bundle\Entity\****Repository")
 * @ORM\HasLifecycleCallbacks()
 */
class MyEntity
{

/**
 * @var integer $id
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var \DateTime $created_at
 * 
 * @ORM\Column(name="created_at", type="datetime")
 */
private $created_at;

/**
 * @var \DateTime $updated_at
 * 
 * @ORM\Column(name="updated_at", type="datetime", nullable="true")
 */
private $updated_at;

/**
 * Set created_at
 *
 * @param datetime $createdAt
 */
public function setCreatedAt($createdAt)
{
    $this->created_at = $createdAt;
}

/**
 * Get created_at
 *
 * @return datetime 
 */
public function getCreatedAt()
{
    return $this->created_at;
}

/**
 * Set updated_at
 *
 * @param datetime $updatedAt
 */
public function setUpdatedAt($updatedAt)
{
    $this->updated_at = $updatedAt;
}

/**
 * Get updated_at
 *
 * @return datetime 
 */
public function getUpdatedAt()
{
    return $this->updated_at;
}

/**
 * @ORM\PrePersist()
 */
public function executePrePersist()
{
    $this->created_at = new \DateTime();
}

/**
 * @ORM\PreUpdate()
 */
public function executePreUpdate()
{
    $this->updated_at = new  \DateTime();
}
}

在這里發布之前,我已經添加:

print_r(get_class($value))

到有問題的地方的DateTimeTzType.php知道它接收了哪種數據,並且出現以下錯誤:

Warning: get_class() expects parameter 1 to be object, string given 

因此,似乎它在接收字符串而不是DateTime對象,然后失敗,因為字符串沒有format()方法。

我正在使用Symfony 2.0.9。 我想念什么嗎?

好像您的setCreatedAt()和getCreatedAt()並未指定它們需要DateTime作為類型,這是Doctrine期望的。

您可以確保在調用這些函數時創建DateTime對象,也可以修改方法以檢查是否提供了字符串作為輸入,並在需要時創建對象。 通常只將日期的字符串表示形式作為第一個參數發送給DateTime構造函數即可。

是我的錯 我在實體中的其他地方有另一個具有DateTime類型的字段,並且在持久化之前將字符串傳遞給它。 我確信這是createdAt字段。 感謝xdebug,對不起,這篇文章。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM