【CakePHP 2.x】getLastInsertId() を検証してみた

getLastInsertId() という便利メソッドがある。
これは Model で保存したデータの最新主キーを返してくれる。

ただ、いまいち挙動が信用できない。
具体的に言うと、
getLastInsertId() は 該当モデル(テーブル)の最新主キーを返すのか、
保存したデータに割り振られた主キーを返すのか・・・。

ということで、以下のコードで検証してみた。

<?php

App::uses('AppController', 'Controller');

class TopsController extends AppController {
    public $name = 'Tops';
    public $uses = array('Category', 'Title', 'Note');
    public function index(){
        $this->autoRender = false;
        $this->Note->save(array(
            'id'=>null,
            'message'=>'test ttt',
            'dumy1'=>'ok'
        ), false);
        sleep(10);
        echo 'ID : '.$this->Note->id;
        echo '<br>';
        echo 'LastID : '.$this->Note->getLastInsertId();
        $this->render('/Errors/test');
    }


    public function index2(){
        $this->autoRender = false;
        $this->Note->save(array(
            'id'=>null,
            'message'=>'test ttt',
            'dumy1'=>'ok'
        ), false);
        echo 'ID : '.$this->Note->id;
        echo '<br>';
        echo 'LastID : '.$this->Note->getLastInsertId();
        $this->render('/Errors/test');
    }}   

index と index2 の違いは、
sleep() があるかどうか。

まずは index を実行し、1件のレコードを保存する。
保存後は10秒スリープする。

10秒スリープの間に index2 を実行する。
index2 はスリープしないので、
そのまま主キーが表示される。

index は10秒スリープ後に getLastInsertId() を実行して、
主キーの値を表示させる。

これで index2 の値と同じであれば、
getLastInsertId() は該当テーブルの最新主キーを取得することになる。
値が異なれば、保存したデータの主キーを取得することになる。

で、結果はどうかというと・・・・
保存したデータの主キーを取得していました。
まあ、当たり前か・・・。
じゃないと、複数ユーザーが使う場合に整合性取れなくなる・・・。

ちなみに、プチ検証として、
$this->Model->id とgetLastInsertId() の値も比較してみた。
結果、同じでした。
どっちを使ってもいいのかな・・・?