I am fairly new to CakePHP and having a problem getting last inserted id. My schema is as follows:
CREATE TABLE IF NOT EXISTS `markets` (
`id` int(11) NOT NULL,
`name` varchar(20) NOT NULL,
`region_code` varchar(5) NOT NULL,
`country_code` varchar(255) NOT NULL,
`language` varchar(255) NOT NULL,
`default_language` varchar(10) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
ALTER TABLE `markets`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `region_code` (`region_code`),
ADD KEY `locale` (`country_code`),
ADD KEY `language` (`language`);
ALTER TABLE `markets`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8;
And this is my logic:
$this->loadModel('Market');
if( isset($this->request->data['Market']) ) {
$this->Market->set($this->request->data);
if( $this->Market->validates() ) {
$this->Market->save($this->request->data);
echo $this->Market->id; //displays zero
echo $this->Market->getLastInsertID(); //also displays zero
}
}
It all looks good in MySQL though, as id gets auto incremented there as it's supposed to be.
P.S. I just inserted another record and here's what's returned:
array (size=1)
'Market' =>
array (size=8)
'name' => string 'Japan' (length=5)
'region_code' => string 'JP' (length=2)
'country_code' => string 'JP' (length=2)
'language' => string 'ja_JP' (length=5)
'default_language' => string 'ja_JP' (length=5)
'modified' => string '2015-04-23 09:11:34' (length=19)
'created' => string '2015-04-23 09:11:34' (length=19)
'id' => string '0' (length=1)
Ok, so for now I just added a function called 'getMarketLastInsertId' to the Market model, which takes 'country_code' (unique key in the table) as a parameter and returns the last id... Thanks