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条)

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)