Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returned inserted id using $this->query in cakephp

Tags:

cakephp

how i can get the inserted id when I insert a record in this way using cakephp $this->query (" insert into [tablename] ([colname]) values([colvalue]);

like image 281
SMSM Avatar asked Nov 05 '09 10:11

SMSM


3 Answers

Assuming you are using MySQL you could perform the following query after you did the insert:

$array_with_id = $this->query('select last_insert_id() as id;');

But as mentioned by kouak, the usual way to insert data is to use the save() method. If you use this method, the id of the inserted record will then be automatically available in the $id property of the respective model.

like image 194
dhofstet Avatar answered Sep 21 '22 02:09

dhofstet


If you use the the save() method you can get the id like so:

$this->Model->save($data);
$id = $this->Model->id;
like image 37
Shard Avatar answered Sep 20 '22 02:09

Shard


Cake's model class has a function that gets the last inserted id:

$this->Model->getLastInsertID()

line 2584 in {project-folder}/cake/libs/model/model.php

like image 44
cp3 Avatar answered Sep 24 '22 02:09

cp3