duanmie9682 2014-02-07 05:51 采纳率: 100%
浏览 34
已采纳

如何设置symfony实体类中某些字段的值

I have the entity class in symfony like this

/**
 * @var datetime $createDate
 * @ORM\Column(name="create_date", type="datetime", nullable=false)
 *
 */
private $createDate;

/**
 * @return datetime
 */
public function getCreateDate(){
    return $this->createDate;
}

public function setCreateDate(\DateTime $createDate){
    $this->createDate=new \DateTime('today');
    return $this;
}

basically i want to set the date to today while saving.

I am using JSON which gets are serilaized object and then i am deserializing it.

but this date object is not in that serilaizer and i want to set it when i persist the entity

This is simple case but i want to do some calculation on date and then save it.

  • 写回答

2条回答 默认 最新

  • duanli9930 2014-02-07 07:40
    关注

    There are different approaches. The simplest one is to set the createDate in the constructor:

    public function __construct()
    {
      $this->createDate = new \DateTime();
    }
    

    The second one is - like Alexander already described - using a lifecycle callback method:

    /**
     * @ORM\Entity()
     * @ORM\HasLifecycleCallbacks()
     */
    class yourEntityClass
    {
      // ...
    
      /**
       * @ORM\PrePersist
       */
      public function prePersist()
      {
        $this->createDate = new \DateTime();
      }
    }
    

    The third one is using the Doctrine Extensions bundle, which comes with an annotation for that:

    /**
     * @var datetime $createDate
     * @ORM\Column(name="create_date", type="datetime", nullable=false)
     * @Gedmo\Timestampable(on="create")
     */
    private $createDate;
    

    This makes especially sense, if you also want to use additional behaviours that come with this bundle, for example the sluggable behaviour or the translatable behaviour.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题