2012-09-20 40 views
1

我需要爲列生成唯一值。我想增加表中最後一個插入的值。遞增最後插入的值CakePHP

我想這一點,但都無濟於事

if($this->request->is('post')){ 
    $code = $this->Department->find('first', array(
     'fields' => 'Department.code', 
     'order' => 'Department.code DESC' 
    )); 
    $code += 1; 
    $this->data['Department']['code'] = $code; 
    if($this->Department->save($this->request->data)){ 
     $this->Session->setFlash('New department added.'); 
     $this->redirect(array('action' => 'add')); 
    } 
} 

謝謝!

回答

3

您正在保存$ this-> request-> data但您將您的數據存入$ this-> data

嘗試與此:

if($this->request->is('post')){ 
    $code = $this->Department->find('first', array('fields' => 'Department.code','order' => 'Department.code DESC')); 
    $code += 1; 
    $this->request->data['Department']['code'] = $code; 
    if($this->Department->save($this->request->data)){ 
     $this->Session->setFlash('New department added.'); 
     $this->redirect(array('action' => 'add')); 
    } 
} 
+0

你也可以只使用原子updateAll使用它()來在單個快速查詢中完成所有工作 - 請參閱http://stackoverflow.com/questions/8689203/incrementing-cakephp-database-field-by-a-value。 – mark

+0

試試這個http://stackoverflow.com/a/11020439/1239506 –

0

$ ID = $這個 - >用戶 - > getLastInsertId();

通過此功能,您將獲得最後插入的ID,現在增加它的價值,並要使用或ncrement這個ID,並將其保存在數據庫中