1

I need to generate a unique value for a column. I want to increment the last inserted value in the table.

I've tried this, but to no avail

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'));
    }
}

Thanks!

bancer
  • 7,475
  • 7
  • 39
  • 58
fart-y-goer
  • 747
  • 3
  • 8
  • 27

2 Answers2

3

You are saving $this->request->data but you put your data in $this->data.

Try with this:

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'));
    }
}
Davor Lozic
  • 116
  • 5
  • you could also just use the atomic updateAll() to do everything in a single and fast query - see http://stackoverflow.com/questions/8689203/incrementing-cakephp-database-field-by-a-value. – mark Sep 20 '12 at 08:43
0

$id = $this->User->getLastInsertId ();

by this function you will get last inserted id and now increment its value and use it where you want to use or ncrement this id and save it in your database

Jhanvi
  • 594
  • 3
  • 17