自动创建日期-注释- Codeigniter 2和原则2



我正在使用Doctrine 2与Codeigniter 2,我想在表中的给定字段中自动生成插入的当前日期。

类文件:

<?php 
namespace models;
/**
 * @Entity
 * @Table(name="workers")
 */
class Workers {
    /**
     * @Id
     * @Column(type="integer", nullable=false)
     * @GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @Column(type="string", length=255, unique=true, nullable=false)
     */
    protected $email;
    /**
     * @var datetime $created_on
     * 
     * @gedmo:Timestampable(on="create")
     * @Column(type="datetime")
     */
    protected $created_on;

    /** @PrePersist */
    function onPrePersist()
    {
        $this->created_on = date('Y-m-d H:i:s');
    }
    /* Setters & Getters */
    public function setEmail($email){ $this->email = $email; }
    public function getEmail(){ return $this->email; }
}

INSERT方法:

$worker = new modelsWorkers();
$worker->setEmail($data['email']);
$this->em->persist($worker);
$this->em->flush();

每次我在表"工人"中插入新记录时,总是有created_on字段NULL而不是插入日期。我做错了什么?

如果我错了,请纠正我。但我知道好像Doctrine不支持违约。在php中,比如

/**
 * @Column(type="string", length=255)
 */
private $something = "blabla";

看你的源代码,我看到你正在使用gedmo扩展学说。我说的对吗?所以你有两种方法来做到这一点。

1)只是使用Doctrine,没有Gedmo
仔细阅读本手册,你会注意到@HasLifecycleCallbacks注解。

所以你应该编辑你的代码为;

类文件

<?php 
  namespace models;
 /**
  * @Entity
  * @Table(name="workers")
  * @HasLifecycleCallbacks
  */
class Workers {
 /**
  * @Id
  * @Column(type="integer", nullable=false)
  * @GeneratedValue(strategy="AUTO")
  */
 protected $id;
 /**
  * @Column(type="string", length=255, unique=true, nullable=false)
  */
 protected $email;
 /**
  * @var datetime $created_on
  * @Column(type="datetime")
  */
protected $created_on;
 /** @PrePersist */
 function onPrePersist()
 {
     //using Doctrine DateTime here
     $this->created_on = new DateTime('now');
 }
 /* Setters & Getters */
 public function setEmail($email){ $this->email = $email; }
 public function getEmail(){ return $this->email; }
}

2)使用Gedmo

如果你更喜欢使用Gedmo Timestampable扩展,那么只需删除prepersist函数,因为Gedmo会为你做所有的事情。我还检查了我的源代码。我希望我的预测没有错。

类文件

<?php 
  namespace models;
 /**
  * @Entity
  * @Table(name="workers")
  */
class Workers {
 /**
  * @Id
  * @Column(type="integer", nullable=false)
  * @GeneratedValue(strategy="AUTO")
  */
 protected $id;
 /**
  * @Column(type="string", length=255, unique=true, nullable=false)
  */
 protected $email;
 /**
  * @var datetime $created_on
  * @Column(type="datetime")
  * @gedmo:Timestampable(on="create")
  */
protected $created_on;
 /* Setters & Getters */
 public function setEmail($email){ $this->email = $email; }
 public function getEmail(){ return $this->email; }
}

对于原则2.3,使用

/**
 * @var datetime $created_on
 * 
 * @Column(type="datetime", options={"default"="CURRENT_TIMESTAMP"})
 */
protected $created_on;

您可以尝试以下操作:

/**
 * @var timestamp $created_on
 * 
 * @Column(type="timestamp", default="CURRENT_TIMESTAMP")
 */
protected $created_on;

最新更新