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 (

Now I want to get last inserted id… HOW?

Haven’t used it yet

Try with


Check the doc -

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. ;)


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

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

try below:

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

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

$id = $transaction->getLastInsertID();