2013-04-11 28 views
1

在afterSave中,獲取關於$this的信息的最佳方法是什麼?在模型回調中獲取模型數據的正確方法

例如。如果我debug($this->read()),我得到了我正在使用的當前記錄(相關模型等)所需的一切。

array(
    'Comment' => array(
     'id' => '12', 
     'user_id' => '38' 
     'body' => 'test', 
     'created' => '2013-04-11 18:56:26', 
     'modified' => '2013-04-11 18:56:26' 
    ), 
    'User' => array(
     'password' => '*****', 
     'id' => '38', 
     'username' => 'example', 
     'created' => '2013-01-26 18:25:39', 
     'modified' => '2013-01-26 18:25:39', 
     'first_name' => '', 
     'last_name' => '' 
    ) 
) 

但這並不意味着我再次查詢數據庫? $this不應該已經包含了所有這些信息嗎?

什麼是得到$this->read()的結果的正確方法,或者這是正確的方法?

回答

2

這是正確的方式($this->read),根據你想要什麼信息你剛剛保存的記錄。 例如,如果你正在做的插入,和你的$數據(使用像Comment->save($data))是:

array(
    'Comment' => array(
     'id' => '12', 
     'user_id' => '38' 
     'body' => 'test', 
     'created' => '2013-04-11 18:56:26', 
     'modified' => '2013-04-11 18:56:26' 
    ), 
    'User' => array(
     'password' => '*****', 
     'id' => '38', 
     'username' => 'example', 
     'created' => '2013-01-26 18:25:39', 
     'modified' => '2013-01-26 18:25:39', 
     'first_name' => '', 
     'last_name' => '' 
    ) 
) 

和我意味着什麼這樣,那麼$this->data仍會有剛剛保存相同的信息。 $this->data僅在afterSave後設置爲false。

不過,如果你這樣做

$this->Comment->saveField('body', 'othertest'); 

$this->data數組中的afterSave將只包含類似

Array 
(
    [id] => 6 
    [body] => 'othertest' 
    [modified] => 2013-04-11 15:17:45 
) 

換句話說,如果你想獲得所有信息不管在save()中作爲參數傳遞的數據如何,您都必須執行$ this-> read()(或find())。

+0

+1尼斯和完整的答案 – thaJeztah 2013-04-11 20:43:21

0

您應該能夠訪問像這樣的數據:

public function afterSave($var = null){ 
    parent::afterSave($var); 
    echo '<pre>'; 
    print_r($this->data); 
    echo '</pre>'; 
    die(); 
} 

嘗試的代碼,看到期待通過輸出。這將使您可以訪問已發佈的數據,如果保存成功,該數據應與記錄匹配。你使用的是什麼版本的CakePHP,你試圖做什麼?

閱讀雖然很好。