How can I get last inserted id after saving model?
How can I get last inserted id after saving model?
Hi,
If You are using:
if($model->save())
{
// 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
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 : http://www.yiiframework.com/forum/index.php/topic/17764-save-doesnt-set-id/page__gopid__138995#entry138995
I hope it could help someone
using
if(isset($_POST[‘ArticleCategory’])) {
$model->attributes=$_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";
if($student->save()){
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.