Last inserted id

Having problem in getting Last inserted id…

I am inserting record by this…




$command = Yii::app()->db->createCommand();


$command->insert('attachments', array(

    'name' => $filename,

    'create_time' => date('Y-m-d H:i:s'),

    'create_user_id' => Yii::app()->user->id

));



Using Yii Query Builder (http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder)

Now I want to get last inserted id… HOW?

Haven’t used it yet

Try with


Yii::app()->db->lastInsertID

Check the doc - http://www.yiiframework.com/doc/api/1.1/CDbConnection#lastInsertID-detail

Tried it but not compatible with Yii query builder :( but now i have created a model class for attachments extend it to CActiveRecords for this purpose and also for saving it by it…

if you are using with CActiveRecords …then you can use a $model->id after saving data.which will return you a last inserted id…

but i am very surprised why a solution suggested by mdobma is not working for you…!!

Why not?

Command is an instance of CDbCommand, which has a getConnection function which returns a CDbConnection which has a getLastInsertID function.

Same as calling Yii::app()->db->getLastInsertID I presume.

Just try it.

Don’t call getLastInsertID on the CDbCommand but on it’s parent. ;)

Edit:


$command = Yii::app()->db->createCommand();

$last_id = Yii::app()->db->getLastInsertID(();

try below:

$transaction = Yii::app()->db;

$register = $transaction->createCommand()->execute();

$id = $transaction->getLastInsertID();