fart-y-goer
fart-y-goer

Reputation: 739

Increment last inserted value CakePHP

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!

Upvotes: 1

Views: 561

Answers (2)

Jhanvi
Jhanvi

Reputation: 592

$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

Upvotes: 0

Davor Lozic
Davor Lozic

Reputation: 116

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

Upvotes: 3

Related Questions