2012-02-25 75 views
5
最後插入值

我已經做了一個模型form.In的字段都像獲取Yii中

id 
firstname 
lastname 
description 
created_at 
updated_at 
created_by 
updated_by 

我已經做了必要的CRUD的Form.Now我想獲得一個額外的字段最後插入id在查看文件。所以如何獲得該值?爲了獲得該值,我應該在CRUD中做出任何必要的更改?任何幫助和建議都將非常有價值。

+0

重複: //stackoverflow.com/questions/9456132/getting-last-inserted-id-from-mysql-in-yii和http://stackoverflow.com/questions/9436264/ascending-form-numbers-in-yii – Avanche 2012-02-29 11:45:40

回答

21

你可以得到最後插入的ID是這樣的:

Yii::app()->db->getLastInsertId(); 

更多信息,請參見Yii documentation

+0

ID不是ID。大寫D Yii :: app() - > db-> getLastInsertID(); – 2017-09-08 07:27:05

1

如果您的目標是獲得分配給您剛剛保存的模型的標識,那麼在做$model->save()後,只需執行$model->id即可將其恢復。

2

如果$model->id不起作用,則使用Yii::app()->db->getLastInsertId()getPrimaryKey()

+0

'Yii :: app() - > db-> getLastInsertId()'似乎更好,因爲它可以在模型之外的任何地方使用(比如在遷移中),並且不會被討論[在這裏](http:// www。 yiiframework.com/forum/index.php/topic/6566-how-to-know-the-last-record-id-inserted/page__view__findpost__p__33653)。但是,任何地方 - 很好的答案(+!)。謝謝。 – trejder 2015-03-24 09:13:27

2

您還可以獲取其他模型的最後一個插入的ID。

$std_id = Students::model()->findAll(array('order' => 'admission_no DESC','limit' => 1)); 

      foreach($std_id as $f) { 

       echo "Last Inserted Admission No:".$f['admission_no']; 
       } 

你可以最後插入的ID在同一模型

Yii::app()->db->getLastInsertID(); 
0

參考鏈接:Here

$model->primaryKey or 
$model->id // this is your primary key item 
2

Yii2最後插入的ID可以使用

得到
Yii::$app->db->getLastInsertedID(); 

增加了尋找同一個問題的答案的人yii2

0

在Yii2最後插入的ID可以開始使用

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

不使用http的

Yii::$app->db->getLastInsertedID();