How to get last insert id before inserting data in cakephp 3.x?


#1

In Cake 3.x, I know the following method to get last id.

$entity = $this->MyModel->newEntity($this->request->data())
$result= $this->MyModel->save($entity); //Statement as result
$id = $result->id;

But this is only for after inserting data. Is there any way to get id before inserting data?


#2

If the data is not inserted how you suppose to get the id, this is not possible. Btw what exactly you want to achieve? If you want some modification just before saving the entity, you can use the callbacks.


#3

I just want to know the last id that I used previous before saving a data. I am not sure, Is this available or not in cakephp? Anyway thanks for your reply.


#4

Ok so do you want to get the last id which exist in table or you want the id that you are trying to save?


#5

G’day,

Setup: Windoze 7 Pro x64 SP1; Apache 2.4.23 (Win64);MySQL 5.7.15 (mysqli, mysqlnd, pdo_mysql 5.0.12); PHP 7.0.11; CakePHP 2.9.1;

I have used the following line to redirect to the view method on the newly created ‘id’:

which is inserted in the add method after the line ‘if ($this->MODEL->save($this->request->data))’:

public function add() {
	if (array_key_exists('Cancel', $this->request->data)) {
		$this->Flash->error('Cancelled adding new group.');
		return $this->redirect(array('action' => 'index'));
	} elseif ($this->request->is('post')) {
		$this->Group->create();

			if ($this->Group->save($this->request->data)) {
/* this line */		$id_max = strval(max($this->Group->find('list', array('fields' => array('id')))));
			$this->Flash->success('The group has been added.');
			return $this->redirect(array('action' => 'view', $id_max));
		} else {
			$this->Flash->error('The group could not be added! Please, try again.');
		}
	}
	return $this->render('edit');
} // end add()

I use the maximum value found because I have intermediate ‘id’ indices missing due to record deletions over time, so the count(‘id’) value is always (in MY case) too low.

McS