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!

2 Answers 2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.