2010-01-13 19 views
15

如何检查字段是否已更改?学说听众 - 只有在字段发生变化时才运行

我只想在preSave()中触发一个动作,只有当特定字段已经改变时,e.q.

public function preSave() { 
    if ($bodyBefore != $bodyNow) { 
     $this->html = $this->_htmlify($bodyNow); 
    } 
} 

的问题是如何得到这个$bodyBefore$bodyNow

回答

23

请不要再次获取数据库!这适用于Doctrine 1.2,我还没有测试过较低版本。

// in your model class 
public function preSave($event) { 
    if (!$this->isModified()) 
    return; 

    $modifiedFields = $this->getModified(); 
    if (array_key_exists('title', $modifiedFields)) { 
    // your code 
    } 
} 

请查看documentation

-1

尝试了这一点。

public function preSave($event) 
{ 
    $id = $event->getInvoker()->id; 
    $currentRecord = $this->getTable()->find($id); 

    if ($currentRecord->body != $event->getInvoker()->body) 
    { 
     $event->getEnvoker()->body = $this->_htmlify($event->getEnvoker()->body); 
    } 
} 
+0

当我给'preSave()'添加'$ event'参数时,根本不执行该方法。 – takeshin 2010-01-19 09:36:22

+0

您使用的是哪个版本的学说? – Travis 2010-01-19 18:13:05

+0

我使用Doctrine 1.2.1 – takeshin 2010-03-17 00:04:14

3

特拉维斯的答案几乎是正确的,因为问题是当你做原则查询时,对象被覆盖。所以解决方案是:

public function preSave($event) 
{ 
    // Change the attribute to not overwrite the object 
    $oDoctrineManager = Doctrine_Manager::getInstance(); 
    $oDoctrineManager->setAttribute(Doctrine::ATTR_HYDRATE_OVERWRITE, false); 

    $newRecord = $event->getInvoker(); 
    $oldRecord = $this->getTable()->find($id); 

    if ($oldRecord['title'] != $newRecord->title) 
    { 
    ... 
    } 
} 
相关问题