如何获取最后插入记录 - Yii 2

How to get last insert record - Yii 2

我正在申请创建条形码 在我的应用程序中,我想创建 Barang 但在发行单中我希望从最后一张发行单自动填写发行单 我该怎么做才能解决它?

这是我的看法

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model backend\models\Barang */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="barang-form">

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'rm_code')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'nama_barang')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'berat')->textInput(['maxlength' => true]) ?>



    <?= $form->field($model, 'issue_slip')->textInput(['maxlength' => true]) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

 <div class="row">
    <?= $form->field($model, 'berat')->textInput(['maxlength' => true]) ?>
    <?php echo  \Yii::$app->db->getLastInsertId('{{barang}}');?>

  </div>

渲染前在控制器中

public function actionCreate()
{
    $model = new Barang();
    $modelForSlip = Barang::find()->orderBy(['id'=> SORT_DESC])->one();
    $model->issue_slip = $modelForSlip->issue_slip;

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

       $model->waktu = date('Y-m-d h:m:s');
       $model->user = \Yii::$app->user->identity->username;
       $model->save();

        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
         //$model->issue_slip= \Yii::$app->db->getLastInsertId();
    }
}

假设这是您的创建函数:

 public function actionCreate()
    {
        $model = new Modal();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
             return $this->redirect(['update', 'id' => $model->Id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

然后重定向到最后插入的新页面 ID 现在让你像这样更新功能

 public function actionUpdate($id)
        {
            $model2 = Model::findOne($id);
            $model = new Modal();
 $model->issue_slip = $model2['issue_slip'];




            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->Id]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }

YII2中你可以轻松获取save()函数后最后插入的记录

喜欢

 $model->save();
echo $model->Id 

或者你想得到的任何列 而不是 issue_slip 你可以使用你想要的任何列