Get the last item saved

Hello

I need to get id in moment that I save data. For example, I save my datas using this way:




//simple example to save

$myModel = new MyBodel();

$myModel->attributes=$_POST["MyModel"];

if($myModel->save()){

  $find_last_data = MyModel::find()->orderBy(['id'=> SORT_DESC])->limit(1)->one();

  $id = $find_last_data["id"];

}

else

 echo "erro";



But is it the better way? There is the possibility of when I use this line:

$find_last_data = MyModel::find()->orderBy([‘id’=> SORT_DESC])->limit(1)->one();

Other register is inserted in my table and I get wrong id? Many people use my app in same time.

Hi!

Not completly sure, but as far as I understood your model should have the correct ID after it was saved.

Not needed to execute extra find method…

Example:




$myModel = new MyBodel();

$myModel->attributes=$_POST["MyModel"];

if($myModel->save()){

  $last_id = $myModel->id; // should have ID of currently saved data... 

}



At least this works for me… ;)

Regards

Thanks

Your example worked very well




$model = new MyModel();

if ($model->load(Yii::$app->request->post()) && $model->save()) {

   $last_id=$model->id; 

}