Get last inserted id

How can I get last inserted id after saving model?


If You are using:



	// than you can get id just like that


	$model->id // this is inserted item id


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

I prefer this method

1 Like

Thanx, I have got it!

If after save(), $model->id is not updated, it means you affect $model->id before save.

Please check this thread for more details :

I hope it could help someone ;)


if(isset($_POST[‘ArticleCategory’])) {


        $config = Yii::app()->params->notEndcodeFields;// is array('id');

        //Clean data

        $p = new CHtmlPurifier();

        $model->description = $p->purify($model->description);

        foreach($model->attributes as $key=>$val){

            if(!in_array($key, $config)){

                $model->$key = CHtml::encode($val);




But I thinks $model->primaryKey is better.

I want last id of respective table. What should I do in such scenario.

How do you mean by respective table?

Here are example:

$student = new Student();

$student->name = "John";


	echo $student->id;//This is the ID of a newly inserted student in a database


The same logic applies if you are working with any other database table.