php 在 Yii 中获取最后插入的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9443615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting last inserted value in Yii
提问by NewUser
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.
我已经为 Form 做了必要的 CRUD。现在我想为视图文件中最后插入的 id 获取一个额外的字段。那么如何获取该值?要获取该值,我应该在 CRUD 中进行任何必要的更改吗?任何帮助和建议都将是高度适用。
回答by fivedigit
You can get the last inserted ID like this:
您可以像这样获取最后插入的 ID:
Yii::app()->db->getLastInsertId();
See the Yii documentationfor more information.
有关更多信息,请参阅Yii 文档。
回答by Aaron
If your goal is to get the id that was assigned to the model that you just saved, then after you do $model->save()
, simply do $model->id
to get it back.
如果您的目标是获取分配给您刚刚保存的模型的 id,那么在您执行之后$model->save()
,只需执行$model->id
即可将其取回。
回答by Kaletha
If $model->id
wouldn't work then use Yii::app()->db->getLastInsertId()
or getPrimaryKey()
.
如果$model->id
不起作用,则使用Yii::app()->db->getLastInsertId()
或getPrimaryKey()
。
回答by Elango Mani
you can also get the last inserted id of another model.
您还可以获取另一个模型的最后插入的 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'];
}
or
或者
you can last inserted id in the same model
您可以在同一模型中最后插入 id
Yii::app()->db->getLastInsertID();
回答by Kuldeep Dangi
In Yii2
last inserted id can be get using
在Yii2
最后插入的 id 中可以使用
Yii::$app->db->getLastInsertedID();
added for the people looking for the answer of same question in yii2
为寻找相同问题答案的人添加 yii2
回答by user5510975
In Yii2 last inserted id can be get using
在 Yii2 中最后插入的 id 可以使用
Yii::$app->db->getLastInsertID();
not use
不使用
Yii::$app->db->getLastInsertedID();