2010-01-13 52 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) 
    { 
    ... 
    } 
} 
相關問題