str_pad 不能在 Mysql 领域使用 Yii2

str_pad don't works in Mysql field using Yii2

我在 Yii2 控制器中有这个创建操作:

public function actionCreate2()
    {
      $searchModel = new BibliografieSearch();
      $searchModel = new CodiciSearch();
      $dataProvider = $searchModel->search(Yii::$app->request->queryParams);    

        $model = new Elenchi();  
        $model->Modified = date( 'y-m-d' );
        
        
        if ($model->FogliDaO) {
            $model->FogliDaO = str_pad($model->FogliDaO, 8, "0", STR_PAD_LEFT);
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            
            return $this->redirect(['index', 'sort' => '-IDElenco']);
        }

        return $this->render('create2', [
            'model' => $model,
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel


        ]);
    }

现在,如果我在字段 (FogliDaO) 中写入“28v”并保存新记录,Mysql 数据库中的结果始终是“28v”,而不是“0000028v”。我哪里错了? (FogliDaO 是 VARCHAR)。我需要帮助。 非常感谢!!!!

如果您想更改 $model 的内容,您必须在 load() 函数之后和 save() 函数之前分配填充值..否则您将覆盖分配

public function actionCreate2()
{
  $searchModel = new BibliografieSearch();
  $searchModel = new CodiciSearch();
  $dataProvider = $searchModel->search(Yii::$app->request->queryParams);    

    $model = new Elenchi();  
    
    

    if ($model->load(Yii::$app->request->post()) ) {
        $model->Modified = date( 'y-m-d' );
        
        if ($model->FogliDaO) {
            $model->FogliDaO = str_pad($model->FogliDaO, 8, "0", STR_PAD_LEFT);
        }
        $model->save();
        return $this->redirect(['index', 'sort' => '-IDElenco']);
    }

    return $this->render('create2', [
        'model' => $model,
        'dataProvider' => $dataProvider,
        'searchModel' => $searchModel


    ]);
}

$model->load() 函数将相应的模型数据从 $_POST 复制到您的实际(新)模型..所以如果您在 load() 函数之前分配填充值,则该值将丢失,因为load 用 $_POST 内容覆盖这个值