【问题标题】:Doctrine date in save override / before save保存覆盖/保存前的教义日期
【发布时间】:2011-01-30 06:36:00
【问题描述】:

我有一个带有日期字段“date_of_birth”(symfony 表单日期)的 Doctrine 模型,由用户填写,所有工作 100% 按预期保存到数据库,但是在模型 save() 方法中我需要检索保存前该字段的值。我的问题是,当尝试获取日期值时,如果它是新记录则返回空字符串,如果它是现有记录则返回旧值

public function save(Doctrine_Connection $conn = null)
{
      $dob = $this->getDateOfBirth(); // returns empty str if new and old value if existing
      $dob = $this->date_of_birth; //also returns empty str

      return parent::save($conn);
 }

如何在保存数据之前检索该字段的值

【问题讨论】:

    标签: symfony1 doctrine save


    【解决方案1】:

    在 Doctrine 1.2 中,您可以覆盖 preSave 伪事件:

    // In your model class
    public function preSave($event) {
       $dob = $this->getDateOfBirth();
    
       //do whatever you need
    
       parent::preSave($event);
    }
    

    In Doctrine 2.1 the function names changed.

    【讨论】:

    • 链接损坏... :/
    • 另外 Carlos 没有必要对我投反对票,因为 Doctrine Project 多年来(现在已经 6 年半)没有保持他们的链接
    【解决方案2】:

    学说中的一般伪事件使用“新”值,但是有 getModified() 方法,它完全符合您的需要。

    $modifiedFields = $this->getModified(true);
    if(isset($modifiedFields['date_of_birth'])) { //index is available only after change
      echo $modifiedFields['date_of_birth']; //old value
    }
    

    more info from doc about getModified()

    【讨论】:

      猜你喜欢
      • 2019-09-20
      • 2011-11-29
      • 2011-08-17
      • 2020-07-16
      • 1970-01-01
      • 2014-02-16
      • 2018-02-18
      • 2014-08-24
      • 2018-07-26
      相关资源
      最近更新 更多