1
我試圖將CakePHP從1.3遷移到2.0。而現在,我遇到了一個小問題,就是將值插入特定的字段。下面是我在1.3版本中所做的代碼:如何在cakePHP 2.0的數據庫字段中保存特定值?
function add() {
if(isset($_SESSION['User']['id'])){
if(!empty($this->data)) {
if($this->Ad->save($this->data)){
//saving the uID in table ads
$this->data['Ad']['uID'] = $_SESSION['User']['id'];
$this->data['Ad']['DatePosted'] = DboSource::expression('NOW()');
$this->data['Ad']['IP'] = $_SERVER['REMOTE_ADDR'];
$this->Ad->save($this->data, FALSE);
$this->Session->setFlash('The post was successfully added!');
$this->redirect(array('action'=>'index'));
}
else{
$this->Session->setFlash('The post was not saved. Please try again.', 'alert-message', array('class'=>'error'));
}
}
}
else{
$this->Session->setFlash('You have to login first to access control panel');
$this->redirect(array('controller'=>'users','action'=>'login'));
}
//for setting the category of advertisement
$adcats = $this->Ad->Adcat->find('list',array('fields'=>array('id','Description')));
$this->set(compact('adcats'));
//for setting the type of advertisement
$adtyps = $this->Ad->Adtyp->find('list',array('fields'=>array('id','Description')));
$this->set(compact('adtyps'));
}
現在,這裏是我的代碼中,我想包括用戶ID(表示爲UID),後日(代表作爲DatePosted)和用戶的IP地址。
public function add() {
if($this->Session->read('user_id')){
if($this->request->is('post')) {
if($this->Ad->save($this->request->data)){
//saving the uID in table ads
//$this->data['Ad']['uID'] = $this->Session->read('user_id');
//$this->data['Ad']['DatePosted'] = DboSource::expression('NOW()');
//$this->data['Ad']['IP'] = $_SERVER['REMOTE_ADDR'];
$this->Ad->uID = $this->Session->read('user_id');
$this->Ad->DatePosted = DboSource::expression('NOW()');
$this->Ad->IP = $_SERVER['REMOTE_ADDR'];
$this->Ad->save($this->request->data);
$this->Session->setFlash('The post was successfully added!');
$this->redirect(array('action'=>'index'));
}
else{
$this->Session->setFlash('The post was not saved. Please try again.', 'alert-message', array('class'=>'error'));
}
}
}
else{
$this->Session->setFlash('You have to login first to access control panel');
$this->redirect(array('controller'=>'users','action'=>'login'));
}
//for setting the category of advertisement
$adcats = $this->Ad->Adcat->find('list',array('fields'=>array('id','Description')));
$this->set(compact('adcats'));
//for setting the type of advertisement
$adtyps = $this->Ad->Adtyp->find('list',array('fields'=>array('id','Description')));
$this->set(compact('adtyps'));
}
現在,我的問題是如何保存我之前提到過的那三個字段?
非常感謝@Ross的迴應。但是,我有另一個問題。如果我將DatePosted的字段名更改爲已創建,並且您提到它會自動奇蹟地添加創建的發佈時間,那麼我可以再次詢問此示例代碼嗎?實際上,您提供的代碼正在工作,但只有DatePosted無效,可能或者可能存在我需要包含的必需代碼。致命錯誤:未找到'DboSource'類 – bowmeow 2012-03-03 01:51:43
不能確定該錯誤 - 可能使用2.0中更改了'DboSource',找不到任何關於它的文檔。關於自動魔法,你只需要在你的表中有一個名爲'created','modified'或'updated'(或全部三個)的字段,即'datetime'和默認值'null'。 Cake應該完成剩下的工作 - 你甚至不需要調整任何控制器代碼。 – Ross 2012-03-03 18:42:13
我明白了。感謝您的幫助Ross。 – bowmeow 2012-03-05 01:48:57