个性化阅读
专注于IT技术分析

YII数据库更新记录示例

点击下载

要更新数据库中的记录, 请按照下列步骤操作。我们已经将Yii2文件夹命名为update。

步骤1创建模型文件

在frontend / models文件夹中创建一个模型文件child.php。

<?php 
namespace app\models; 
 
use Yii; 
 
class Child extends \yii\db\ActiveRecord 
{ 
    /** 
     * @inheritdoc 
     */ 
    public static function tableName() 
    { 
        return 'child'; 
    } 
     
    /** 
     * @inheritdoc 
     */ 
    public function rules() 
    { 
        return [ 
            [['name', 'meaning', 'gender'], 'required'], [['name', 'meaning'], 'string', 'max' => 100], [['gender'], 'string', 'max' => 15] 
        ]; 
    } 
}

步骤2在控制器中添加操作

在控制器文件ChildController.php中添加更新操作actionEdit。

<?php 
namespace frontend\controllers; 
 
use Yii; 
use app\models\Child; 
use yii\web\Controller; 
 

/** 
* manual CRUD 
 **/ 
class ChildController extends Controller 
{  
    /** 
     * Create 
     */ 
    public function actionCreate() 
    { 
        
        $model = new Child(); 
 
        // new record 
        if($model->load(Yii::$app->request->post()) && $model->save()){ 
            return $this->redirect(['index']); 
        } 
                 
        return $this->render('create', ['model' => $model]); 
    } 

    /** 
     * Read 
     */ 
    public function actionIndex() 
    { 
        $child = Child::find()->all(); 
         
        return $this->render('index', ['model' => $child]); 
    } 

    /** 
     * Edit 
     * @param integer $id 
     */ 
    public function actionEdit($id) 
    { 
        $model = Child::find()->where(['id' => $id])->one(); 
 
        // $id not found in database 
        if($model === null) 
            throw new NotFoundHttpException('The requested page does not exist.'); 
         
        // update record 
        if($model->load(Yii::$app->request->post()) && $model->save()){ 
            return $this->redirect(['index']); 
        } 
         
        return $this->render('edit', ['model' => $model]); 
    } 
    }

步骤3建立检视档案

在frontend / view / child文件夹中创建一个文件edit.php。

<?= $this->render('child_view', [ 
    'model' => $model, ]) ?>

步骤4运行

在浏览器上运行它。

http://localhost/dbb/frontend/web/index.php?r = child%2Fedit&id = 6

YII更新记录1

单击更新, 信息将被更新。

YII更新记录2

查看快照中的最后一行, 数据已更新。

下载此示例

赞(0)
未经允许不得转载:srcmini » YII数据库更新记录示例

评论 抢沙发

评论前必须登录!