简体   繁体   中英

Getting last inserted value in Yii

I have already made a model for form.In that the fields were like

id
firstname
lastname
description
created_at
updated_at
created_by
updated_by

I have made necessary CRUD for Form.Now I want to get one extra field for last inserted id in view file.So how to get that value?To get that value should I make any necessary changes in CRUD?Any help and suggestions will be highly appriciable.

You can get the last inserted ID like this:

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

See the Yii documentation for more information.

如果您的目标是获取分配给您刚刚保存的模型的ID,那么在执行$model->save() ,只需执行$model->id即可将其恢复。

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

you can also get the last inserted id of another model.

$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'];
                }

or

you can last inserted id in the same model

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

In Yii2 last inserted id can be get using

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

added for the people looking for the answer of same question in yii2

Reference Link : Here

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

In Yii2 last inserted id can be get using

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

not use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM