[英]CakePHP 1.3 $this -> save () doesn't execute a query
使用 CakePHP 1.3 我正在嘗試將一些數據保存到 MySQL 數據庫中。 數據不是來自表單,但為了模仿它,我將數據放在 $this -> data 數組中,如下所示:
$this -> data = Array (
'User' => Array (
'last_login' => date ('Y-m-d H:i:s')
)
);
這將創建一個看起來與默認 Cake 數據數組完全相同的數組。 到目前為止,一切都很好。
接下來,我調用下面的function:
if ($this -> User -> save ($this -> data))
{
echo $this -> User -> id;
}
else
{
echo 'Save failed';
}
它總是出現“保存失敗”,表明數據沒有正確保存。 我嘗試以多種方式對此進行調試:
我檢查了我的用戶 model 或 AppModel 中是否存在 beforeSave 或 beforeValidate function 以及這些是否返回 true。 (他們做到了。)
我在 default.ctp 中回顯了$this -> Session -> flash ()
。 它什么也沒說。
我在 default.ctp 中回顯了$this -> element ('sql_dump')
。 我沒有看到任何我期望的查詢的跡象,這證實了我對查詢不執行而不是失敗的期望。
從我的 controller 我回應了$this -> validationErrors
。 它是空的,所以驗證似乎沒問題。
我試圖在我的$this -> data array
中提供正確的索引以進行保存,如下所示:
$this -> User -> save ($this -> data['User']);
我檢查了我是否通過$this -> loadModel ('User')
加載了我的用戶 model(我做了)。
請注意,我嘗試在我的 AppController 中執行此操作(這就是我手動加載 model 的原因)。 更具體地說:它在 AppController 中的beforeFilter ()
function 中。 這個 function 在我的應用程序的所有其他 Controller 中的beforeFilter ()
function 中被調用(我檢查了這個)。
目前,我不知道是什么原因造成的。 有人對此有任何想法嗎?
您在保存之前沒有指定用戶 ID,因此 CakePHP 不知道將日期保存到哪一行。 實際上,您是在要求 CakePHP 只保存一個日期,而不指定在哪里。 我現在離開我的 webdev 盒子,但我相信這就是你要找的。
if( ! isset( $this->User->id ) ) {
$this->User->create();
}
$this->User->saveField('last_login', date(DATE_ATOM));
請參閱此頁面了解更多信息。 順便說一句,如果您想按照最初的方式進行操作,我認為就是這樣:
if( ! isset( $this->User->id ) ) {
$this->User->create();
$myId = $this->User->getLastInsertID();
} else {
$myId = $this->User->id;
}
$this -> data = Array (
'User' => Array (
'id' => $myId
'last_login' => date ('Y-m-d H:i:s')
)
);
if ($this -> User -> save ($this -> data))
{
echo $this -> User -> id;
}
else
{
echo 'Save failed';
}
如果你想更新你的 last_login
$this->User->id
$this->User->saveField('last_login', date ('Ymd H:i:s'));
或者如果你保存所有記錄,那么你有這種類型的數組,你必須有“id”。
您通過 session 或無論如何獲得的這個“id”
$this -> data = Array ( 'User' => Array ( 'id' => $myId 'last_login' => date ('Ymd H:i:s') ) );
if ($this -> User -> save ($this -> data)) { echo $this -> User -> id; } else { echo 'Save failed'; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.