Returns the inserted identifier using $ this-> query in cakephp

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

+6
cakephp
source share
4 answers

Assuming you are using MySQL, after performing the insert, you can execute the following query:

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

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

+3
source share

If you use the save () method, you can get the identifier like this:

 $this->Model->save($data); $id = $this->Model->id; 
+3
source share

The Cake model class has a function that receives the last inserted id:

 $this->Model->getLastInsertID() 

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

+2
source share

Please use this method to get the last paste id in cakephp2

 $data['yourModelName']['yourTableField'] = POstdata $data['yourModelName']['yourTableField'] = time(); $data['yourModelName']['yourTableField'] = 1; $data['yourModelName']['yourTableField'] = time(); $this->yourModelName->create(); $this->yourModelName->save($data,false); $sessionInserted_id = $this->yourModelName->getInsertID(); 
0
source share

All Articles