Yii :: app ()->db->lastInsertId returns 0 - MySQL

Good afternoon,

By invoking the save method, execute the function Yii :: app () -> db-> lastInsertId I value returns 0, even if it has been saved successfully.

I’ve tried to do this in a new connection to avoid duplicate connections, but without success:

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



$id = Yii::app()->db->lastInsertID;


var_dump($id); die; //return 0

My table is with AUTO_INCREMENT.

Thank you!

You can get it very easily:


    $last_insert_id = $model->id;


if ($model->save()) {

    $model->refresh(); // necessary for new records only, so you could refresh only if ($model->isNewRecord)

    var_dump($model->id); // returns the newly inserted Id


1 Like